簡體   English   中英

是否有從頭開始的 Python re.sub?

[英]Is there a Python re.sub that starts from the end?

是否有 Python 的re.sub()版本類似於str.rfind並從最后一個匹配項開始搜索?

我想對字符串中的最后一個匹配項進行正則表達式替換,但 stdlib 中似乎沒有現成的解決方案。

如果你是字面意思,沒有。 這不是正則表達式引擎的工作方式。

您可以反轉字符串並使用反轉模式應用re.sub(pattern, sub, string, count=1) ,就像評論中所說的那樣。

或者您可以構造一個僅匹配最后一個匹配項的正則表達式,如下所示:

>>> import re
>>> s = "hello hello hello hello hello world"
>>> re.sub(r"hello(?!.*hello.*$)", "hay", s)
'hello hello hello hello hay world'

您可以以普通方式使用re.sub ,但以(.*)開頭的正則表達式以匹配盡可能多的字符串,然后在替換中您可以使用\1包括未更改的部分.*匹配.

>>> re.sub("(.*)a", r"\1A", "bananas")
'bananAs'

(注意這里的r以確保\被逐字傳遞給re.sub並且不被視為開始轉義序列。)

暫無
暫無

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

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