Python 如何使用正则表达式匹配单词之间的文本?
我希望在Python中的预处理器定义之间匹配文本 在本例中,我希望匹配删除文本,以便删除第2..4行,例如:Python 如何使用正则表达式匹配单词之间的文本?,python,regex,Python,Regex,我希望在Python中的预处理器定义之间匹配文本 在本例中,我希望匹配删除文本,以便删除第2..4行,例如: #if 1 # if 0 Remove me # endif Keep me #endif 使用此正则表达式可以删除文本,但*不会在第一个#endif处停止: def remove_if0(string): pattern = r"(^\s*#\s*if\s+0\b.*^\s*#\s*endif\b)" regex = re.compile(pattern, re.
#if 1
# if 0
Remove me
# endif
Keep me
#endif
使用此正则表达式可以删除文本,但*
不会在第一个#endif
处停止:
def remove_if0(string):
pattern = r"(^\s*#\s*if\s+0\b.*^\s*#\s*endif\b)"
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
return regex.sub("", string)
有没有一种方法可以不通过一个学期的点球读数来匹配配对?例如^\s*\s*endif\b
我尝试了
(?!word)
,例如:(?!^\s*\s*endif\b)*
-但没有成功。解决方案是使用ungreedy*?
(感谢@bobble bubble)
下面是一个正常工作的Python函数:
def remove_if0(string):
pattern = r"(^\s*#\s*if\s+0\b.*?^\s*#\s*endif)"
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
return regex.sub("", string)
解决方案是使用ungreedy
*?
(感谢@bobble bubble)
下面是一个正常工作的Python函数:
def remove_if0(string):
pattern = r"(^\s*#\s*if\s+0\b.*?^\s*#\s*endif)"
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
return regex.sub("", string)
使用它!谢谢重复的可能重复项有相同的答案,但问题更为特殊(也是
.net
,尽管这并不总是重要的)。使用它!谢谢复制品的可能复制品有相同的答案,但问题更为特殊(同样是.net
,尽管这并不总是重要的)。