使用正则表达式(JavaScript)获得第一句

时间:2018-08-27 19:38:25

标签: javascript regex

我已经为JavaScript创建了一个正则表达式,该表达式应该“很聪明”地从文本/句子字符串中获得第一句话。我用RegExr来创建和测试它:

https://regexr.com/3uhoj

但是,当我实际实现该正则表达式时:

rustup self uninstall

在我的JavaScript代码中,我使用split,除了第一句话,我得到了所有内容。输出如下:

/.*(.)(?=\s[A-Z])/g

如果有任何RegEx管理员以我的方式看到错误和/或有任何提示或解决方案,我将不胜感激。

谢谢!

PS:是的,我已经在搜索这个...

1 个答案:

答案 0 :(得分:0)

像这样尝试:

const regex = /.*?(\.)(?=\s[A-Z])/;
const str = `© 2018 Telegraph Publishing LLC Four area men between the ages of 18 and 20 were arrested early this morning on a variety of charges in an overnight burglary at the Tater Hill Golf Course in Windham. According to a Vermont State Police press release, at about 2:30 a.m. Saturday, troopers got a report that […]`;
let m;

if ((m = regex.exec(str)) !== null) {
console.log(m[0]);
}

我使用惰性正则表达式匹配而没有g标志,只是检索第一个结果。

或者使用否定的字符类,因为它更有效:/^[^.]+\.(?= [A-Z])/