我的单词边界正则表达式有什么问题?

时间:2017-09-18 14:25:23

标签: regex python-3.x word-boundary

我有以下小Python脚本:

import re

def main ():
    thename = "DAVID M. D.D.S."
    theregex = re.compile(r"\bD\.D\.S\.\b")
    if re.search(theregex, thename):
        print ("you did it")
main ()

它不匹配。但是,如果我稍微调整正则表达式并删除最后一个。它确实有效,如下:

\bD\.D\.S\b

我觉得我很擅长理解正则表达式,但这令人困惑。我对\ b(单词边界)的理解应该是非字母数字(和下划线)的零宽度匹配。所以我希望

"\bD\.D\.S\.\b"

匹配:

D.D.S.

我错过了什么?

2 个答案:

答案 0 :(得分:1)

这不符合你的想法。

r"\bD\.D\.S\.\b"

以下是explanation of that regex,其中列出了相同的示例:

D.D.S.   # no match, as there is no word boundary after the final dot
D.D.S.S  # matches since there is a word boundary between `.` and `S` at the end

单词边界是单词字符之间的零宽度匹配(\w[0-9A-Za-z_]加上您的语言环境定义的其他“字母”和非单词字符(\W,这是前一课的倒置)。点(.)不是单词字符,因此D.D.S. (注意尾随空格)在以下位置具有单词边界(仅限!):\bD\b.\bD\b.\bS\b. (我没有逃脱点因为我正在说明边界这个词,而不是正则表达式。)

我假设您正在尝试匹配行尾或空格。有两种方法可以做到这一点:

r"\bD\.D\.S\.(?!\S)"   # by negation: do not match a non-whitespace
r"\bD\.D\.S\.(?:\s|$)" # match either a whitespace character or end of line

我已将以上正则表达式解释链接改进为explain the negation example above(请注意…/1中的第一个结尾,而…/2中的第二个结尾;请随意在那里进一步实验,这很好和互动)。

答案 1 :(得分:0)

  • \.\b匹配.bla - 检查.
  • 之后的单词字符
  • \.\B相反的匹配bla.但不是bla.bla - 检查.之后的非单词
\bD\.D\.S\.\B