Python Forum

Full Version: Regex pattern match
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to match all characters between "\x" and "\xk" for instance: in the string "\x - \xo 2:2 \xk".

I set my pattern as:

pattern = "\\x.+\\xk"
replaceWith = "<b>"
irec=re.sub(pattern, replaceWith, irec)
However, this gives me an error in my replace. I also tried:
pattern = r"\x.+\xk"
replaceWith = "<b>"
irec=re.sub(pattern, replaceWith, irec)


But this gives same error: re.error: incomplete escape \x at position 0
This is the double whammy. "\" is the start of an escape sequence for a str literal and it is the start of a special sequence in a regex pattern. Use one of these:
pattern = r"\\x.+\\xk"
pattern = "\\\\x.+\\\\xk"
You need the "\\x" to tell Python that the "\x" is not the start of a hex number. This makes the python str look like "\x.+\xk". But "\" in a pattern string is also meaningful, so we need another backslash to tell regex that we really want the characters '\' and 'x'.
Thank you!