简体   繁体   中英

Python regex: substitute all occurrence of a certain string NOT after a specific character

How can I substitute all occurrence of a certain string NOT after a specific character in Python?

For example, I want to substitute all occurrence of abc NOT with a x before them with def . Here is the code:

re.sub(r'(^|[^x])abc', r'\1def', string)

If the string doesn't have consecutive abc s, the code works perfectly. However, if I have string='abcabc' , the code won't work. Is there any way to solve this problem?

With a negative lookbehind assertion (?<!...) (ie not preceded by) :

(?<!x)abc

In a replacement:

re.sub(r'(?<!x)abc', r'def', string)
result = re.sub("(?<!x)abc", "def", subject)
  • The negative lookbehind (?<!x) asserts that what precedes is not x
  • abc matches abc
  • We replace with def

Reference

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