我有这个正则表达式:(?<![A-Z])(?<=[.!?])\s(?=[A-Z]) 它将一段分成句子(基于每个空格)。
我在这段中使用了它:Did he know that J. Smith is a name? The term is most commonly applied to the placing of a warship in active duty with its country's military forces. The ceremonies involved are Often rooted in centuries old naval tradition. I.D. is a wonderful word.
它在“J. Smith”上中断,因为它认为“.”代表一个句子的结束。
我正在使用 re.split() 并打印出数组,用换行符分隔值
这是上面段落的输出:
Did he know that J.
Smith is a name?
The term is most commonly applied to the placing of a warship in active duty with its
country's military forces. (no newline at beginning of sentence)
The ceremonies involved are Often rooted in centuries old naval tradition.
I.D. is a wonderful word.`
它适用于“I.D.”但为什么不是“J. Smith”呢?从逻辑上讲,它应该...
我想让它检测字符串中的这个结构:
没有大写字母+句号/?/!+空格+大写字母
请您参考如下方法:
lookbehind(或 lookahead)是一个零宽度的断言——也就是说,它在断言为真的任何点匹配一个零长度的字符串。
特别是,这意味着,如果您在正则表达式中有两个连续的后向(或前向)断言,则只有当它们都匹配在同一点时,它们才会匹配。
因此,(?<![A-Z])(?<=[.!?])如果前一个字符不是 A-Z 范围内的大写字母则匹配和 如果它是字符之一 .!? .显然,后者的断言暗示了前者,因此 (?<![A-Z])您的正则表达式的一部分没有实际效果。
看起来您想要断言前一个字符是.!? 它前面的那个不是大写字母。如果是这样,一种解决方案是替换 (?<![A-Z])与 (?<![A-Z].) .
附言。您的原始正则表达式没有拆分“I.D. is ”的原因是 \s 的第一个点之后没有空格。匹配,并且第二个句点之后的空格后面没有按照您的前瞻断言的要求跟随大写字母。
