I need to replace some value in a string using regular expression in Python. Sample strings
hello @abc.def blar blar => hello abc.def blar blar
hello @abc.def.gh blar blar => hello abc.def.gh blar blar
hello @abc.def=gh blar blar => hello abc.def=gh blar blar
hello (@abc.def)gh blar blar => hello (abc.def)gh blar blar
hello @abc.def_gh blar blar => hello abc_1.def_gh blar blar
Note when @abc is followed by space, dot, equal sign or round bracket, @abc will be replaced with abc, otherwise @abc will be replaced with abc_1.
I tried to take a two step approach:
- Replace @abc followed by the white listed chars with abc.
- Replace remaining @abc with abc_1
I have no problem with step 2, but for the first step, I'm able to detect the right pattern, but not sure how to reserve the character following @abc
For example,
str = "hello @abc.def blar blar"
print(re.sub(r'@abc[\.\s=]+', 'abc', str))
This would produces a result without the "." char
hello abcdef blar blar
Appreciate if anyone can advise on this.