regex 正则表达式检查多个单词中是否有一个不是开头

yk9xbfzb  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(125)

我试图从一段文本中拆分句子,我目前的解决方案可以工作,但它并不总是工作。

text.replaceAll(/[^Mr|^mr|^Mrs|^mrs|^Ms|^ms](\.|\?|\!)\s[A-Z]/g, r => r.replace(/\s/, "{break}")).split("{break}");

它的工作方式应该是先找到一个句点,然后是一个空格,后面是一个大写字母,Mr、Mr、Mrs、Mrs、Ms或ms除外。它目前是这样做的,除非句子以s、m或r结尾。我知道这是因为[]与其中的任何字符匹配,我的问题是如何编写它,以便它能按我的要求工作(匹配整个单词,而不是单个字符)
失败的字符串示例如下

"A string with words. A new string."

一个通过

"A string. A new string."
dgiusagp

dgiusagp1#

如何拆分一个句子,而不打断姓名标题。

你喜欢正则表达式,你想把结果分组,只抓取句点。然后我们把我们用的作为标识符组,并用{break}条目替换为$1变量。

let text = "A string with words. Mr. Andrews wrote a new string. It went something like Mrs. Doubtfire's best line. But what if 3.1 people want to sign up for Gecko? What if it ends in a question mark?";

const OPExample = text.replace(/(?<!Mr|Mrs|Ms|Dr|Sr)([\.?\??\!?]) ([A-Z])/gi, "$1{break}$2")

const SplitLines = OPExample.split("{break}");

console.log(OPExample); // "A string with words.{break}Mr. Andrews wrote a new string.{break}It went something like Mrs. Doubtfire's best line.{break}But what if 3.1 people want to sign up for Gheko?{break}What if it ends in a question mark?"

console.log(SplitLines); // ["A string with words.","Mr. Andrews wrote a new string.","It went something like Mrs. Doubtfire's best line.","But what if 3.1 people want to sign up for Gheko?","What if it ends in a question mark?"]

Codepen

相关问题