使用正则表达式在句子中查找标题大小写

Finding title case within sentence using regex

我正在尝试使用 Regex 来提取句子中出现的标题大小写的短语和单词。

目前的努力:

(?:[A-Z][a-z]+\s?)+  

此正则表达式代码应用于下面的示例句子时会发现那些显示为粗体的词。但我需要忽略像 This 和 Whether(句子开头)这样的词。

例句:

This 是一个例句,用于检查此代码的实际值是否有效或无效取决于结果。

期望:

这是一个例句,用于检查此代码的实际值。是否有效无效取决于结果。

有用代码:

import regex as re

text='This is a Sample Sentence to check the Real Value of this code. Whether it works or Not depends upon the result. A State Of The Art Technology is needed to do this work.'
rex=r'(?<!^|[.!?]\ )\b[A-Z][a-z]+(?:\ [A-Z][a-z]+)*\b'

matches = re.finditer(rex,text)
results = [match[0] for match in matches]
print(results)

结果:

['Sample Sentence', 'Real Value', 'Not', 'State Of The Art Technology']

如果你的句子总是单一的 spaced,你可以对一个字母使用正向后视,并使用 space 来找到 title-cased 表达式的开头:

(?<=[a-z,] )(?:[A-Z][a-z]+(?![a-z]).)+

此正则表达式允许表达式以标点符号结尾,而不仅仅是 space(例如 the Final Result.)。

Demo on regex101

假设你的正则表达式风格支持 Lookbehinds,我会使用这样的东西:

(?<!^|\.\ )\b[A-Z][a-z]+(?:\ [A-Z][a-z]+)*\b

Demo.

这将支持前面有缩写、标点符号或除句号(上一句结尾)之外的几乎所有内容的单词。


编辑:

根据 Nick 在评论中的建议,最好在 Lookbehind 中包含 !? 以支持以其中任何一个结尾的句子,而不仅仅是时期:

(?<!^|[.!?]\ )\b[A-Z][a-z]+(?:\ [A-Z][a-z]+)*\b

Demo.