regex - 正则表达式中\b和\>,\<有什么区别?

标签 regex word-boundary

现在我很困惑。

我在正则表达式备忘单中找到了这个

\b    word boundary
\<    start of word
\>    end of word

但是在《掌握正则表达式》一书中,它告诉我这一点

\<    word boundary
\>    word boundary

\b 和有什么区别和\> \<在正则表达式中?

最佳答案

摘要

\b    word boundary
\<    word boundary; specifically, word boundary followed by a word; ie, start of word
\>    word boundary; specifically, word followed by word boundary; ie, end of word

如果你有一个像“bob”这样的词,那么\b单词边界模式将返回两个零长度匹配,它们相当于单词的开头和结尾。这很有用,因为可以让您挑选字符串中的单词。因此字符串“foo bar”与 \b 匹配。对于这两个单词的 start-end-start-end 有四个空匹配。

在此基础上,您可以看到 \<将为您提供单词开头的位置(foo 的开头和 bar 的开头有 2 个匹配)和 \>单词的结尾(foo 的结尾和 bar 的结尾有两个匹配)。

所以你可以等同于 \b\<像这样:

  \< 
is equivalent to
  start-of-word 
is equivalent to
  word-boundary-followed-by-word 
is equivalent to
  \b(?=\w)

我认为你的“掌握正则表达式”书有点模糊,并且描述了 \<\>作为单词边界,应该更精确,分别区分为“单词边界(专门针对单词开头)”和“单词边界(专门针对单词结尾)”。

Python 示例:

>>> re.compile(r'\b').findall('foo bar')
['', '', '', '']
>>> re.compile(r'\b(?=\w)').findall('foo bar')
['', '']

请注意,python 不支持 \<\> 。这是一个说明单词边界为何有用的示例。我们可以选出整个单词的 BAR,而不是包裹在 foo 内的 BAR:

>>> re.compile(r'\bBAR\b').findall('foBARo BAR')
['BAR']

关于regex - 正则表达式中\b和\>,\<有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27723018/

相关文章:

c++ - 正则表达式 - 计算所有数字

Javascript - 正则表达式 - 字边界 (\b) 问题

javascript - 匹配任何非单词字符(不包括变音符号)

java - 如何使用 DFA 正则表达式匹配器实现正则表达式断言/环视(即\b 样式词边界)

Java 正则表达式排序\b

python - 用于匹配重复(未知)子字符串的正则表达式

regex - 如何用powershell替换每行的第一部分和最后一部分

regex - Postgres 的正则表达式

regex - vim 正则表达式 : negative backreferences?

Java 正则表达式字边界