我有一個模板,我需要在 Python 中使用 Regex 替換其中的一部分。這是我的模板:(請注意,兩個評論之間至少有一個新行)
hello
how's everything
<!--POSTS:START-->
some text
<!--POSTS:END-->
Some code here
我想替換Python 之間的<!--POSTS:START-->所有內容。<!--POSTS:END-->所以我制作了<!--POSTS:START-->\n([^;]*)\n<!--POSTS:END-->圖案,但它也包括<!--POSTS:START-->在內<!--POSTS:END-->。
這是我想要的:
re.sub('...', 'foo', message)
# expected result:
hello
how's everything
<!--POSTS:START-->
foo
<!--POSTS:END-->
Some code here
謝謝。
uj5u.com熱心網友回復:
您可以使用捕獲組作為開始和結束標記,并在目標替換字串中將它們參考為 \1、\2 等。
如果文本多次出現,<!--POSTS:START-->...<!--POSTS:END-->則正則運算式 with.*?將替換這些組中的每一個。如果'?洗掉正則運算式,然后它將洗掉從第一組開始到最后一組結束的所有文本。
嘗試這個:
import re
s = '''
hello
how's everything
<!--POSTS:START-->
some text
<!--POSTS:END-->
Some code here
'''
# for multi-line matching need extra flags in the regexp
s = re.sub(r'(<!--POSTS:START-->\n).*?(\n<!--POSTS:END-->)', r'\1foo\2', s, flags=re.DOTALL)
# this inlines the DOTALL flag in the regexp for same result
# s = re.sub(r'(?s)(<!--POSTS:START-->\n).*?(\n<!--POSTS:END-->)', r'\1foo\2', s)
print(s)
輸出:
hello
how's everything
<!--POSTS:START-->
foo
<!--POSTS:END-->
Some code here
uj5u.com熱心網友回復:
檢查這個https://docs.python.org/3/library/re.html
import re
pattern = r"(<!--POSTS:START-->\n).*(\n<!--POSTS:END-->)"
string = """hello
how's everything
<!--POSTS:START-->
some text
<!--POSTS:END-->
Some code here"""
result = re.sub(pattern, r"\g<1>foo\g<2>", string)
print(result)
結果:
hello
how's everything
<!--POSTS:START-->
foo
<!--POSTS:END-->
Some code here
uj5u.com熱心網友回復:
您可以使用以下內容:
import re
new_content = re.sub(
r'(<!--POSTS:START-->\n).*?(?=\n<!--POSTS:END-->)', r"\1foo",
content, flags=re.DOTALL)
標志 DOTALL:制作 '.' 特殊字符完全匹配任何字符,包括換行符。
我正在使用兩件事來做你想做的事
- Group lookahead
"?=":斷言給定的子模式可以在這里匹配,而不消耗字符 - 非貪婪匹配模式 (*?)。這將以非貪婪模式匹配。這樣我們就可以分別得到所有的模式
由于我們使用的是前瞻,\n<!--POSTS:END-->因此不會被消耗,所以我只需要保留第一組并重寫匹配之間的內容。這就是為什么我使用\1foo而不是\1foo\2
如果您只需要修改第一個匹配項,您可以使用count=1
re.sub(..., count=1)
你可以在這兩行之間有任何東西,它會按預期作業
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453903.html
標籤:Python 正则表达式 蟒蛇重新 正则表达式替换 蟒蛇正则表达式
上一篇:從鏈接中提取關鍵字
