codingsplash
codingsplash

Reputation: 5075

Replacing a portion of pattern with regex in Python

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

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?

Upvotes: 1

Views: 78

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

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).

Upvotes: 1

vks
vks

Reputation: 67988

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.

Upvotes: 0

Related Questions