簡體   English   中英

如何用正則表達式替換多個重疊模式?

[英]How to replace multiple overlapping patterns with regex?

我想用and替換所有出現的&&

例如, x&& && &&應該變成x&& and and

我試過re.sub(' && ', ' and ', 'x&& && && ') ,但沒有用,第一個&&已經消耗了空格,所以第二個不匹配。

然后我想到了非捕獲組並嘗試但再次失敗。

我怎么解決這個問題?

您可以在此處使用非單詞邊界。

>>> re.sub(r'\B&&\B', 'and', 'x&& && &&')
'x&& and and'
(?:^|(?<=\s))&&(?=\s|$)

使用lookarounds 。不消耗space只是assert 。見演示。

https://regex101.com/r/sS2dM8/39

re.sub('(?:^|(?<=\s))&&(?=\s|$)', 'and', 'x&& && &&')

輸出: 'x&& and and'

這似乎是一個非常古老的帖子。 任何尋找替代方案的人也可以使用以下正則表達式。

re.sub(r"(\s)(\&\&)(?=(\s))", r"\1and", a)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM