0

Lets assume I have the following string:

string = "xxx abc123 xxx"

I want the regular expression to replace the digits in the string that begin with 'abc'. I have tried the following, but with no luck:

re.sub(r'\d{1,3}\babc','456',string)

Thanks.

3
  • What does your expected output for "xxx abc123 xxx" look like? Commented Jun 1, 2011 at 21:35
  • It should look like 'xxx abc456 xxx' Commented Jun 1, 2011 at 21:37
  • Is it always preceded by 'xxx abc'? Commented Jun 1, 2011 at 21:40

1 Answer 1

5
re.sub(r'(?<=abc)\d{1,3}', '456', string)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. This has been very helpful. After doing some more research on this, I believe this expression is called a: positive lookbehind assertion.

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.