Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why \b doesn't work in python re module? [duplicate]

Tags:

python

regex

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?

like image 325
user2384994 Avatar asked Jan 12 '14 04:01

user2384994


1 Answers

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.)

like image 184
BrenBarn Avatar answered Oct 11 '22 06:10

BrenBarn