Home > Net >  How to replace only alphabet characters in my string using regex?
How to replace only alphabet characters in my string using regex?

Time:01-10

I am having trouble with replacing the alphabet characters in a string that contains special characters.

import re

s = 'F6[ab]\nF3[ab]'
n = 'F6[ab]' # <= want to keep this in my string but want to change 'ab' in the new line
k = 'ab' # <= do not want to keep this in my string
c = '1' # <= change 'ab' -> '1'
re.sub(f'(?!{n}){k}', c, s)
# => 'F6[ab]\nF3[1'
# but I want this output
# => 'F6[ab]\nF3[1]'

CodePudding user response:

You can use grouping in your regex to capture and preserve what you want to keep in final result. Use it in a lambda re.sub like this:

import re

s = 'F6[ab]\nF3[ab]'
n = 'F6[ab]' # <= want to keep this in my string but want to change 'ab' in the new line
k = 'ab' # <= do not want to keep this in my string
c = '1' # <= change 'ab' -> '1'

repl = re.sub(r'('   re.escape(n)   rf')|\b{k}\b',
   lambda m: m.group(1) if m.group(1) else c, s)

Output:

'F6[ab]\nF3[1]'

It makes following regex:

(F6\[ab\])|\bab\b

Code Demo

  •  Tags:  
  • Related