【问题标题】:Python Regex Sentence Finder-Want to Ignore "a.m."Python Regex Sentence Finder - 想要忽略“a.m.”
【发布时间】:2021-01-27 01:17:15
【问题描述】:

我正在开发一个正则表达式来查找句子,我想忽略导致正则表达式在句子结尾之前终止的缩写。例如,我想忽略“a.m.”,使其返回“At 9:00 a.m. the store opens.”而不是“At 9:00 a.m.”。 "

def sentence_finder(x):
    RegexObject = re.compile(r'[A-Z].+?\b(?!a\.m\.\b)\w+[.?!](?!\S)')
    Variable = RegexObject.findall(x)
    return Variable

我在运行 pytest 时得到以下信息:

def test_pass_Ignore_am():
>       assert DuplicateSentences.sentence_finder("At 9:00 a.m. the store opens.") == ["At 9:00 a.m. the store opens."]
E       AssertionError: assert ['At 9:00 a.m.'] == ['At 9:00 a.m...store opens.']
E         At index 0 diff: 'At 9:00 a.m.' != 'At 9:00 a.m. the store opens.'

我做错了什么?

【问题讨论】:

标签: python regex


【解决方案1】:

您可以使用否定的lookbehind来检查在匹配一个点之后,它之前没有a.m.

[A-Z].*?\w[.?!](?<!\ba\.m\.)(?!\S)

说明

  • [A-Z] 匹配一个字符 A-Z
  • .*? 尽可能少匹配除换行符以外的任何字符 0+ 次
  • \w[.?!] 匹配一个单词 char 后跟 . ?!
  • (?&lt;!\ba\.m\.) 否定后向断言直接向左不是a.m.
  • (?!\S) 断言右边的空白边界

Regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-11-08
    • 2012-08-12
    • 2017-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    • 2013-05-07
    相关资源
    最近更新 更多