0

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:

  1. Replace @abc followed by the white listed chars with abc.
  2. 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.

Lee
  • 2,874
  • 3
  • 27
  • 51

0 Answers0