-1

I expect the following pattern:

pattern1=r"\Ar(evolution)?ide\bthe\b(earth)\Z"

to match:

string=r"ride the earth"

Instead the following pattern is matching:

pattern2=r"r"\Ar(evolution)?ide \bthe\b (earth)\Z"

As \b is the blank, why isn't pattern 1 matching the string?

3 Answers3

0

\b isn't a space; it matches the empty string at the beginning or end of a word.

\s is a whitespace character, so r"\Ar(evolution)?ide\sthe\s(earth)\Z" would match.

chepner
  • 497,756
  • 71
  • 530
  • 681
0

\b is not blank, it is break instead:

\b Matches a word boundary position between a word character and non-word character or position (start / end of string).

If you need to match space you need to use \s:

\s Matches any whitespace character (spaces, tabs, line breaks).

Pitto
  • 8,229
  • 3
  • 42
  • 51
0

Read this

Matches the empty string, but only at the beginning or end of a word. A word is defined as a sequence of word characters. Note that formally, \b is defined as the boundary between a \w and a \W character (or vice versa), or between \w and the beginning/end of the string. This means that r'\bfoo\b' matches 'foo', 'foo.', '(foo)', 'bar foo baz' but not 'foobar' or 'foo3'.

So "\b" means not to stick to other words, but it matches empty but not space.

COY
  • 684
  • 3
  • 10