Backslash sequence doesn't match
-
03-07-2021 - |
Pergunta
I want to have a word boundary within a negative lookahead. However, as you can see in the example below this does not appear to work in Python. Is this unsupported? If so, is there a way workaround?
To state the full problem I am trying to solve: I have a regex that I'm using in re.sub
, and there are a couple specific words (like "455") that I want to specifically not match.
In [8]: print re.match('(?!455)455', '455')
None
In [9]: print re.match('(?!455\b)455', '455')
<_sre.SRE_Match object at 0x1108fb440>
Solução
\b
is an escape sequence, and as such it will match the backslash character ASCII 0x08
. You need to escape the backslash or use raw string literals:
>>> print(re.match(r'(?!455\b)455', '455'))
None
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow