1

I am trying something very simple. The string I have is

Hello a1234 World a3456 Python a4567 a4567

I want to find all the words which

  • start with a
  • Have four numbers after it

I want to replace the small 'a' in such occurrences with a 'A'.

re.sub("\ba\d\d\d\d\b','A\d\d\d\d',str)

I know the above regex is wrong. I want the output as

Hello A1234 World A3456 Python A4567 A4567

How do I replace only a portion of the match I get?

Edited with a fresh string

str_check='''
Helloa1256
Hello a1256
Hello a1256
Hello a1256
'''
x=re.sub('\ba(?=\d\d\d\d\b)','A',str_check)
print(x)

Why is the the whole word search failing here?

0

2 Answers 2

1

Use positive lookahead assertion.

re.sub(r'\ba(?=\d{4}\b)','A',string)

Assertions won't consume any characters but asserts whether a match is possible or not. So the above regex matches only the a which was followed by exactly 4 digits. Replacing the matched a with A will give you the desired output.

OR

capturing group

re.sub(r'\ba(\d{4})\b',r'A\1',string)

This would capture the 4 digit number which follows the letter a into a group. Later we could refer the captured characters by specifying it's index number in the replacement part like \1 (refers the first group).

Sign up to request clarification or add additional context in comments.

Comments

0
re.sub(r'\ba(?=\d\d\d\d\b)','A',str)

Just use a lookahead as you just want to capture a single character and not the 4 digits after it.

2 Comments

Thanks! If use \b on a multiline string, this does not do a replace. But it works when I remove \b.Any idea why? Also can you explain a bit about why \b is closed within the bracket and not outside?
@user567 \b is inside lookahead coz we say that find an a which has 4 digits after it and then a \b.So an a which has 5 digits after will not match.for the multiline string can you poast the string you trieed this on

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.