Javascript正则表达式匹配句子

时间:2011-04-19 13:16:05

标签: regex

我有以下示例段落:

以下是我的文字。我的介绍性文本是这个,那个和另一个。我的第二行与以前大致相同,但完全不同。甚至不谈论我的第三行文字。

我想使用正则表达式捕获以下句子:

我的介绍性文本是这个,那个和另一个。

我所拥有的代码是:

(\bMy\sintroductory\sline\sof\stext).*(\.)

但这会使全部文本。我将如何捕获直到第一个完整停止?

2 个答案:

答案 0 :(得分:2)

(\bMy\sintroductory\sline\sof\stext).*?\.

这使*“ungreedy”并且它将尽可能少地匹配。

答案 1 :(得分:2)

注意区别:

(\bMy\sintroductory\sline\sof\stext)[^\.]*\.

对于非常好奇,这里有我的方法和Piskvor的基准代码。

角色类方法:通过Firefox在我的机器上约550毫秒。

var start = (new Date()).getTime();
for(var i=0;i<100000;i++){
"The following is my text. My introductory line of text is the this, that and the other. My second line is much the same as before but completely different. Don't even talk about my third line of text.".match(/(\bMy\sintroductory\sline\sof\stext)[^\.]*\./);
}
var stop = (new Date()).getTime();
alert(stop - start);

非贪婪的方法:通过Firefox在我的机器上大约650毫秒。

var start = (new Date()).getTime();
for(var i=0;i<100000;i++){
"The following is my text. My introductory line of text is the this, that and the other. My second line is much the same as before but completely different. Don't even talk about my third line of text.".match(/(\bMy\sintroductory\sline\sof\stext).*?\./);
}
var stop = (new Date()).getTime();
alert(stop - start);

如果您可以并希望在时间上发表评论。谢谢!

请不要发表有关微优化的意见。我只是好奇;)。