Help with Regexp, \b

A

andrew cooke

This is a bit embarassing, but I seem to be misunderstanding how \b
works in regexps.

Please can someone explain why the following fails:

from re import compile

p = compile(r'\bword\b')
m = p.match(' word ')
assert m

My understanding is that \b matches a space at the start or end of a
word, and that "word" is a word - http://docs.python.org/library/re.html

What am I missing here? I suspect I am doing something very stupid.

Thanks,
Andrew
 
A

andrew cooke

andrew cooke said:
Please can someone explain why the following fails:
        from re import compile
        p = compile(r'\bword\b')
        m = p.match(' word ')
        assert m
[...]
You misunderstand what \b does: it doesn't match a space, it matches a 0
length string on a boundary between a non-word and a word.
[...]

That's what I thought it did... Then I read the docs and confused
"empty string" with "space"(!) and convinced myself otherwise. I
think I am going senile.

Thanks very much!
Andrew
 
J

John Machin

That's what I thought it did...  Then I read the docs and confused
"empty string" with "space"(!) and convinced myself otherwise.  I
think I am going senile.

Not necessarily. Conflating concepts like "string containing
whitespace", "string containing space(s)", "empty aka 0-length
string", None, (ASCII) NUL, and (SQL) NULL appears to be an age-
independent problem :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top