Regexp literally interpret \ t as \ t and not tab

I'm trying to match a sequence of backslash text like a window path.

Now when I match a regexp in python it gets a match, but the module interprets all backslashes and then a valid escape char (i.e. t

) as an escape sequence, which is not what I want.

How can I make him not do this?

Thank you, m

EDIT: well, I missed that the regex matching text that contains a backslash is (. *). I tried the original notation (example in ainser), but it doesn't help in my situation. Or it is wrong for them to do it. EDIT2: This was wrong. Thanks guys, girls!

+2


source to share


2 answers


Use double backslash with r like this

>>> re.match(r"\\t", r"\t")
<_sre.SRE_Match object at 0xb7ce5d78>

      

From the python docs :



When a backslash literal needs to be matched, it must be escaped into a regular expression. With a raw string notation, it means r "\". Without the raw string, you must use "\\", making the following lines of code functionally identical:

>>> re.match(r"\\", r"\\")
<_sre.SRE_Match object at ...>
>>> re.match("\\\\", r"\\")
<_sre.SRE_Match object at ...>

      

+10


source


Always use a prefix r

when defining your regular expression. This will tell Python to treat the string as unprocessed, so it doesn't do any standard processing.



 regex = r'\t'

      

-1


source







All Articles