Difference between \b and \B in regex

2019-01-02 17:20发布

I am reading a book on regular expression and I came across this example for \b:

The cat scattered his food all over the room.

Using regex - \bcat\b will match the word cat but not the cat in scattered.

For \B the author uses the following example:

Please enter the nine-digit id as it

appears on your color - coded pass-key.

Using regex \B-\B matches - between the word color - coded. Using \b-\b on the other hand matches the - in nine-digit and pass-key.

How come in the first example we use \b to separate cat and in the second use \B to separate -? Using \b in the second example does the opposite of what it did earlier.

Please explain the difference to me.

EDIT: Also, can anyone please explain with a new example?

标签: regex
7条回答
心情的温度
2楼-- · 2019-01-02 18:09

\b is a zero-width word boundary. Specifically:

Matches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters.

Example: .\b matches c in abc

\B is a zero-width non-word boundary. Specifically:

Matches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).

Example: \B.\B matches b in abc

See regular-expressions.info for more great regex info

查看更多
登录 后发表回答