0

Python 3

I have recently started reading regex and consider the following case :

If input is AB followed by C or D i want to replace it with EF

So, my char class is [CD] and it should be non-capturing.

Using the re.sub i come up with the following:

re.sub(r'AB(?:[CD])','EF',text)

When i run this code for input ABCZ i get EFZ

Thanks!

1 Answer 1

3

Non-capturing doesn't mean it's not included in the match. It just means it's not captured as a group (so you can't use backreferences like \1 to refer to it).

If you want to specify that [CD] should follow but not be included in the match, you need to use a lookahead:

>>> re.sub(r'AB(?=[CD])','EF','ABCZ')
'EFCZ'
Sign up to request clarification or add additional context in comments.

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.