![]() |
Regex pattern match - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Regex pattern match (/thread-39369.html) |
Regex pattern match - WJSwan - Feb-06-2023 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 RE: Regex pattern match - deanhystad - Feb-06-2023 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'. RE: Regex pattern match - WJSwan - Feb-07-2023 Thank you! |