[英]How to match text between words using 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.MULTILINE | re.DOTALL)
return regex.sub("", string)
有沒有一種方法可以在沒有DOTALL讀過一個學期的情況下與配對配對? 例如^\\s*#\\s*endif\\b
。
我嘗試了(?!word)
,例如: (?!^\\s*#\\s*endif\\b)*
-但沒有用。
解決的辦法是使用不貪婪的.*?
(感謝@ 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.