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?
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)(?![xy])
[xy]
xy
matches a single character in the list xy
(case sensitive)