Skip to content Skip to sidebar Skip to footer

Replace All A In The Middle Of String By * Using Regex

I wanted to replace all 'A' in the middle of string by '*' using regex in python I tried this re.sub(r'[B-Z]+([A]+)[B-Z]+', r'*', 'JAYANTA ') but it outputs - '*ANTA ' I would wan

Solution 1:

Using the non-wordboundary \B. To make sure that the A's are surrounded by word characters:

import re
str = 'JAYANTA POKED AGASTYA WITH BAAAAMBOO 'str = re.sub(r'\BA+\B', r'*', str)
print(str)

Prints:

J*Y*NTA POKED AG*STYA WITH B*MBOO 

Alternatively, if you want to be more specific that it has to be surrounded by upper case letters. You can use lookbehind and lookahead instead.

str = re.sub(r'(?<=[A-Z])A+(?=[A-Z])', r'*', str)

Solution 2:

>>> re.sub(r'(?!^)[Aa](?!$)','*','JAYANTA')
'J*Y*NTA'

My regex searches for an A but it cannot be at the start of the string (?!^) and not at the end of the string (?!$).

Solution 3:

Lookahead assertion:

>>> re.sub(r'A(?=[A-Z])', r'*', 'JAYANTA ')
'J*Y*NTA '

In case if word start and end with 'A':

>>> re.sub(r'(?<=[A-Z])A(?=[A-Z])', r'*', 'AJAYANTA ')
'AJ*Y*NTA '

Post a Comment for "Replace All A In The Middle Of String By * Using Regex"