与字边界相比,正则表达式 (\B) 中的非字边界是什么?

发布于 2024-10-09 08:25:12 字数 35 浏览 0 评论 0原文

与字边界相比,正则表达式 (\B) 中的非字边界是什么?

What are non-word boundary in regex (\B), compared to word-boundary?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野生奥特曼 2024-10-16 08:25:12

单词边界 (\b) 是零宽度匹配,可以匹配:

  • 单词字符 (\w) 和非单词字符 (\W) 或
  • 单词字符与字符串的开头或结尾之间。

在 Javascript 中,\w 的定义是 [A-Za-z0-9_]\W 是其他任何内容。

\b 的否定版本,写作 \B,是一个零宽度匹配,而上面的内容成立。因此它可以匹配:

  • 两个单词字符之间。
  • 两个非单词字符之间。
  • 在非单词字符和字符串的开头或结尾之间。
  • 空字符串。

例如,如果字符串是 "Hello, world!"\b 匹配以下位置:

 H e l l o ,   w o r l d !
^         ^   ^         ^ 

\B 匹配 \b 匹配 <代码>\b 不匹配:

 H e l l o ,   w o r l d !
  ^ ^ ^ ^   ^   ^ ^ ^ ^   ^

A word boundary (\b) is a zero width match that can match:

  • Between a word character (\w) and a non-word character (\W) or
  • Between a word character and the start or end of the string.

In Javascript the definition of \w is [A-Za-z0-9_] and \W is anything else.

The negated version of \b, written \B, is a zero width match where the above does not hold. Therefore it can match:

  • Between two word characters.
  • Between two non-word characters.
  • Between a non-word character and the start or end of the string.
  • The empty string.

For example if the string is "Hello, world!" then \b matches in the following places:

 H e l l o ,   w o r l d !
^         ^   ^         ^ 

And \B matches those places where \b doesn't match:

 H e l l o ,   w o r l d !
  ^ ^ ^ ^   ^   ^ ^ ^ ^   ^
酒中人 2024-10-16 08:25:12

non-word-boundary 的基本目的是创建一个正则表达式,它表示:

  • 如果我们位于 word char 的开头/结尾(\w = [a-zA-Z0-9_]) 确保上一个/下一个字符也是一个单词字符

    例如:“a\B.” ~ “a\w”

    "ab""a4""a_",...但不是"a ", "a."

  • 如果我们位于非单词字符的开头/结尾 (\W = [^a-zA-Z0-9_]) 确保上一个/下一个字符也是一个非单词字符

    例如:“-\B.” ~ “-\W”

    "-.""- ""--",...但不是 "-a", "-1"

对于 word-boundary 它是类似的,但不是确保相邻字符属于同一类(单词字符/非单词汽车),它们需要有所不同,因此名称为单词边界

The basic purpose of non-word-boundary is to created a regex that says:

  • if we are at the beginning/end of a word char (\w = [a-zA-Z0-9_]) make sure the previous/next character is also a word char,

    e.g.: "a\B." ~ "a\w":

    "ab", "a4", "a_", ... but not "a ", "a."

  • if we are at the beginning/end of a non-word char (\W = [^a-zA-Z0-9_]) make sure the previous/next character is also a non-word char,

    e.g.: "-\B." ~ "-\W":

    "-.", "- ", "--", ... but not "-a", "-1"

For word-boundary it's similar but instead of making sure that the adjacent characters are of the same class (word char/non-word car) they need to differ, hence the name word's boundary.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文