[英]Replace string between two strings unless it contains a substring
我有一個多行字符串,其中包含以下形式的以下三行:
Text1 Text2a Text3
Text1 Text2b Text3
Text1 Text2! Text3
我希望用Text4
替換Text1
和Text3
之間的所有文本,除非中間文本包含字符!
. 因此,所需的輸出是:
Text1 Text4 Text3
Text1 Text4 Text3
Text1 Text2! Text3
令c
為上面的多行字符串。 我相信re.sub
是這個問題的自然選擇,所以我嘗試了以下方法:
c = re.sub("Text1(.*?)(?,=\,)Text3", "Text1 Text4 Text3". c, flags=re.DOTALL)
但是,它將每個中間文本替換為Text4
。 也就是說,我得到以下輸出:
Text1 Text4 Text3
Text1 Text4 Text3
Text1 Text4 Text3
我該如何解決這個問題?
我會這樣說:
import re
c = """Text1 Text2a Text3
Text1 Text2b Text3
Text1 Text2! Text3"""
c = re.sub("^Text1(?: [^\s!]+)+ Text3$", "Text1 Text4 Text3", c, flags=re.M)
print(c)
這打印:
Text1 Text4 Text3
Text1 Text4 Text3
Text1 Text2! Text3
以下是對所用正則表達式模式的解釋:
^
從行首開始( re.M
是多行模式)Text1
匹配“文本 1”(?: [^\s!]+)+
然后匹配一個或多個不包含!
的非空白術語Text3
匹配空格和“Text3”$
行尾使用不那么貪婪的。*? 在嘗試匹配下一個模式之前匹配盡可能少的文本以解決此問題。 您還可以使用正向先行斷言 (?=, ) 來確定中間文本中是否存在 : 字符,如以下示例所示:
重新進口
c = """Text1 Text2a Text3 Text1 Text2b Text3 Text1 Text2!Text3"""
c = re.sub(r"Text1(. ?)(?=,)Text3", "Text1 Text2, Text3".c.flags=re.DOTALL) c = re.sub(r"Text1(. ?)Text3 ", "Text1 Text4 Text3", c, flags=re.DOTALL)
打印(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.