Escaping [in Python regular expressions

This reg exp search correctly checks if the string contains harry text:

re.search(r'\bharry\b','[harry] blah',re.IGNORECASE)

However, I need to make sure the string contains [harry]. I tried to escape with various amounts of backslashes:

re.search(r'\b\[harry\]\b','[harry] blah',re.IGNORECASE)
re.search(r'\b\\[harry\\]\b','[harry] blah',re.IGNORECASE)
re.search(r'\b\\\[harry\\\]\b','[harry] blah',re.IGNORECASE)

None of these solutions find a match. What do I need to do?

Thank!

+5
source share
3 answers

The first one is correct:

r'\b\[harry\]\b'

But this will not correspond [harry] blah, since [it is not a symbol of the word, and therefore there is no word boundary. It will only match if there [was a word symbol before [, as in foobar[harry] blah.

+4
source
>>> re.search(r'\bharry\b','[harry] blah',re.IGNORECASE)
<_sre.SRE_Match object at 0x7f14d22df648>
>>> re.search(r'\b\[harry\]\b','[harry] blah',re.IGNORECASE)
>>> re.search(r'\[harry\]','[harry] blah',re.IGNORECASE)
<_sre.SRE_Match object at 0x7f14d22df6b0>
>>> re.search(r'\[harry\]','harry blah',re.IGNORECASE)

\b, . .

+1

, : .

, r"\[harry\]" [harry].

\b . .

\b :

  • ,
  • ,
  • \w - \w ( )

[ ] , , [, \b. , \b, \b ( ).

0

All Articles