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
  • 80,714
  • 11
  • 64
  • 111
Chan
  • 2,855
  • 6
  • 27
  • 50

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
  • 80,714
  • 11
  • 64
  • 111