0

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 abcs, the code works perfectly. However, if I have string='abcabc', the code won't work. Is there any way to solve this problem?

2 Answers 2

3

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

(?<!x)abc

In a replacement:

re.sub(r'(?<!x)abc', r'def', string)
Sign up to request clarification or add additional context in comments.

Comments

2
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.