Using regex in python

I have the following problem. I want to avoid 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 not win here. '\ 1' indicates a special character, and I want to add a '\' before this special character. but using \ 1 removes its special meaning, while \\ 1 also doesn't help.

+3
source share
3 answers

Use r'\\\1'. This is a backslash (escaped, labeled as such \\) followed by \1.

To make sure this works, try:

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

Fingerprints:

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

, , . , 'eFEx\\-x\\?k\\=\\;\\-'; , , print.

+7

re.escape()?

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

'eFEx\\-x\\?k\\=\\;\\-'
+3

Try adding another backslash:

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

Source: https://habr.com/ru/post/1766767/


All Articles