11

It is known that \b means word boundary in regular expression. However the following code of re module in python doesn't work:

>>> p=re.compile('\baaa\b')
>>> p.findall("aaa vvv")
[]

I think the returned results of findall should be ["aaa"], however it didn't find anything. What's the matter?

brandonscript
  • 68,675
  • 32
  • 163
  • 220
user2384994
  • 1,759
  • 4
  • 24
  • 29
  • 2
    (Single quotes disabling escapes isn’t a Python thing; the two types are equivalent.) – Ry- Jan 12 '14 at 04:21

1 Answers1

27

You need to use a raw string, or else the \b is interpreted as a string escape. Use r'\baaa\b'. (Alternatively, you can write '\\b', but that is much more awkward for longer regexes.)

BrenBarn
  • 242,874
  • 37
  • 412
  • 384