Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using regex in python

Tags:

python

regex

i have the following problem. I want to escape all special characters in a python string.

str='eFEx-x?k=;-'

re.sub("([^a-zA-Z0-9])",r'\\1', str)

'eFEx\\1x\\1k\\1\\1\\1'

str='eFEx-x?k=;-'

re.sub("([^a-zA-Z0-9])",r'\1', str)

'eFEx-x?k=;-'

re.sub("([^a-zA-Z0-9])",r'\\\1', str)

I can't seem to win here. '\1' indicates the special character and i want to add a '\' before this special character. but using \1 removes its special meaning and \\1 also does not help.

like image 930
Cheezo Avatar asked Feb 14 '26 05:02

Cheezo


2 Answers

Use r'\\\1'. That's a backslash (escaped, so denoted \\) followed by \1.

To verify that this works, try:

str = 'eFEx-x?k=;-'
print re.sub("([^a-zA-Z0-9])",r'\\\1', str)

This prints:

eFEx\-x\?k\=\;\-

which I think is what you want. Don't be confused when the interpreter outputs 'eFEx\\-x\\?k\\=\\;\\-'; the double backslashes are there because the interpreter quotes it output, unless you use print.

like image 138
Fred Foo Avatar answered Feb 16 '26 17:02

Fred Foo


Why don't you use re.escape()?

str = 'eFEx-x?k=;-'
re.escape(str)

'eFEx\\-x\\?k\\=\\;\\-'
like image 32
eumiro Avatar answered Feb 16 '26 18:02

eumiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!