简体   繁体   中英

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

Is there a version of Python's re.sub() that acts like str.rfind and begins searching from the last match occurrence?

I want to do a regex substitution on the last match in a string, but there doesn't seem to be an out-of-box solution in the stdlib.

If you mean it literally, no. That's not how the regex engine works.

You can either reverse the string and apply re.sub(pattern, sub, string, count=1) with a reversed pattern, like one of the comment said.

Or you can construct a regex that match only the last match, like below:

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

You could use re.sub in the ordinary way but start the regexp with a (.*) to match as much of the string as possible, and then in the replacement you could use \1 to include unchanged the part that the .* matched.

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

(Note here the r to ensure that the \ is passed verbatim to re.sub and not treated as starting an escape sequence.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM