Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use '\Q' and '\E' regex symbols in python?

I thought this should work, but it doesn't:

import re
if re.match("\Qbla\E", "bla"):
    print "works!"

Why it doesn't work? Can I use the '\Q' and '\E' symbols in python? How?

like image 650
wafwaf Avatar asked Mar 07 '12 20:03

wafwaf


1 Answers

Python's regex engine doesn't support those; see §7.2.1 "Regular Expression Syntax" in the Python documentation for a list of what it does support. However, you can get the same effect by writing re.match(re.escape("bla"), "bla"); re.escape is a function that inserts backslashes before all special characters.

By the way, you should generally use "raw" strings, r"..." instead of just "...", since otherwise backslashes will get processed twice (once when the string is parsed, and then again by the regex engine), which means you have to write things like \\b instead of \b. Using r"..." prevents that first processing pass, so you can just write \b.

like image 119
ruakh Avatar answered Nov 14 '22 22:11

ruakh