我遇到以下情况,匹配似乎无法正常进行:
import re
test_case1 = u"I will meet you at 2 pm"
test_case2 = u"I will meet you at 2 p.m."
test_case3 = u"I will meet you at 2 p.m. "
test_case4 = u"I will meet you at 2 p.m. pm "
list_of_words = ['p.m.', 'pm'] # list of words that can be enlarged
# join all words into an or expression and escape all punctuation
joined_words = '|'.join([re.escape(x) for x in list_of_words])
# create a regex that will match a word from the list of words only if it is
# at the start/end of the sentence or it is between two word boundaries
match_regex = r'(^|\b)('+joined_words+r')(\b|$)'
comp_regex = re.compile(match_regex, re.IGNORECASE) # compile the final regex
print comp_regex.findall(test_case1), len(comp_regex.findall(test_case1))
print comp_regex.findall(test_case2), len(comp_regex.findall(test_case2))
print comp_regex.findall(test_case3), len(comp_regex.findall(test_case3))
print comp_regex.findall(test_case4), len(comp_regex.findall(test_case4))
对于4个测试用例,我得到以下结果:
[(u'', u'pm', u'')] 1
[(u'', u'p.m.', u'')] 1
[] 0
[(u'', u'pm', u'')] 1
第一种和第二种情况似乎都可以正常工作,即使我在正则表达式中使用了“ \ b”字边界,第三种也不匹配“ pm”,即使后面有空格。
第四种情况似乎根本不匹配“ pm”,而仅匹配“ pm”。
我似乎无法理解问题所在,因此不胜感激。
Python文档声明以下内容\b
:
匹配空字符串,但仅在单词的开头或结尾处匹配。单词定义为字母数字或下划线字符的序列,因此单词的结尾由空格或非字母数字,非下划线字符指示。请注意,正式地,\ b被定义为\ w和\ W字符之间的边界(反之亦然),或者\ w与字符串的开头/结尾之间的边界,因此被视为字母数字字符的精确字符集取决于在UNICODE和LOCALE标志的值上。例如,r'\ bfoo \ b'匹配'foo','foo。','(foo)','bar foo baz',但不匹配'foobar'或'foo3'。在字符范围内,\ b表示退格字符,以与Python的字符串文字兼容。
根据该定义.
不能标记单词的末尾,因此\b
不能匹配p.m.
。如果您对比赛进行以下更改,您将获得预期的行为:
match_regex = r'(^|\b)('+joined_words+r')(\s|$)'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句