tags:

views:

58

answers:

3

Hi

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

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

However, I need to ensure that the string contains [harry]. I have tried escaping with various numbers of back-slashes:

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 solutuions work find the match. What do I need to do?

Thanks!

A: 
polygenelubricants
See with example when `\b\[harry\]\b` can match: http://www.rubular.com/r/29VeekGwuD
polygenelubricants
+3  A: 

The first one is correct:

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

But this won’t match [harry] blah as [ is not a word character and so there is no word boundary. It would only match if there were a word character in front of [ like in foobar[harry] blah.

Gumbo
arrrrgggghhhh!!! thanks everyone!
A: 
>>> 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)

The problem is the \b, not the brackets. A single backslash is correct for escaping.

Fabian