SingSing Hải
SingSing Hải

Reputation: 33

Python insert at regex position

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?

Upvotes: 1

Views: 71

Answers (2)

X-_-FARZA_ D-_-X
X-_-FARZA_ D-_-X

Reputation: 544

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 \%

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

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.

Upvotes: 2

Related Questions