正则表达式中 \b 和 \B 之间的区别 [英] Difference between \b and \B in regex

查看:203
本文介绍了正则表达式中 \b 和 \B 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本关于正则表达式的书,我遇到了这个 \b 的例子:

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.

使用正则表达式 - \bcat\b 将匹配单词 cat 但不匹配 scattered 中的 cat.

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

对于\B,作者使用以下示例:

For \B the author uses the following example:

请输入九位数的id

出现在您的彩色编码密码上.

appears on your color - coded pass-key.

使用正则表达式 \B-\B 匹配 - 在单词 color -coded 之间.另一方面,使用 \b-\b 匹配 nine-digitpass-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.

为什么在第一个例子中我们使用 \b 来分隔 cat 而在第二个例子中使用 \B 来分隔 -?在第二个示例中使用 \b 与之前所做的相反.

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.

另外,谁能用一个新的例子解释一下?

Also, can anyone please explain with a new example?

推荐答案

混淆源于你的想法 \b 匹配空格(可能是因为b"暗示空白").

The confusion stems from your thinking \b matches spaces (probably because "b" suggests "blank").

\b 匹配单词开头或结尾的空字符串.\B 匹配不在单词开头或结尾的空字符串.这里的关键是-"不是单词的一部分.所以 <left>-<right> 匹配 \b-\b 因为在 - 的两边都有单词边界.另一方面,对于 - <right>(注意空格),破折号两侧没有单词边界.字的边界是左和右一个空格.

\b matches the empty string at the beginning or end of a word. \B matches the empty string not at the beginning or end of a word. The key here is that "-" is not a part of a word. So <left>-<right> matches \b-\b because there are word boundaries on either side of the -. On the other hand for <left> - <right> (note the spaces), there are not word boundaries on either side of the dash. The word boundaries are one space further left and right.

另一方面,当搜索\bcat\b 时,词边界表现得更直观,它符合预期的cat".

On the other hand, when searching for \bcat\b word boundaries behave more intuitively, and it matches " cat " as expected.

这篇关于正则表达式中 \b 和 \B 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆