1

I want to remove ab from a string if ab is not followed by x or y.

For example, if the string is 123ab456, the result should be 123456.

If the string is 123abx456, the result should be123abx456.

How could I use regex to do so?

yatu
  • 86,083
  • 12
  • 84
  • 139
Chan
  • 3,605
  • 9
  • 29
  • 60

1 Answers1

3

Here's a way using re.sub with a negative lookahead:

re.sub(r'ab(?![xy])', '', s)

s = '123ab456'
re.sub(r'ab(?![xy])', '', s)
# '123456'

s = '123abx456'
re.sub(r'ab(?![xy])', '', s)
# '123abx456'

Details

  • ab(?![xy])
    • ab matches the characters ab literally (case sensitive)
    • Negative Lookahead (?![xy])
      • Match a single character present in the list [xy]
      • xy matches a single character in the list xy (case sensitive)
yatu
  • 86,083
  • 12
  • 84
  • 139