Home > Software design >  Python insert at regex position
Python insert at regex position

Time:10-06

I'm working in Python, and I have some strings contain special characters like

"My name is * and he is *".

I want to find all special characters in the string and insert "\" before it so it should be:

"My name is \* and he is \*".

The regex expression I use to spot special characters is r'[-._!"`\'#%&,:;<>=@{}~\$\(\)\*\ \/\\\?\[\]\^\|] '. Is there an easy approach for this in Python?

CodePudding user response:

You need to replace with r'\\\g<0>':

import re
rx = r'[][._!"`\'#%&,:;<>=@{}~$()* /\\?^|-] '
text = "My name is * and he is *"
print( re.sub(rx, r'\\\g<0>', text) )
# => My name is \* and he is \*

See the Python demo.

Replacement pattern details:

  • \\ - a single literal backslash (the double backslash is used since \ is special in replacement patterns)
  • \g<0> - a backreference to the whole match value.

CodePudding user response:

you are just taking it too far with regex a simple replace method can solve this with ease

example:

string = "Hello my name is * I live in *\nI am ^ years old I live with my %"
special_characters = ['*', '^', '%']

for char in special_characters:
    string = string.replace(char, f'\{char}')
    
print(string)

output:

Hello my name is \* I live in \*

I am \^ years old I live with my \%

  • Related