2011-04-19 174 views
3

我有以下几个示例段落:Javascript正则表达式匹配句子

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

我会使用正则表达式喜欢捕捉下面的句子:

我的文字的入门线是这个,那个和其它。

我的代码因而票价为:

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

但这得到所有文本。我将如何捕获,直到第一个完全停止?

回答

2

发现其中的差别:

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

只是为了非常好奇这里是我的方法和Piskvor的一些基准测试代码。

字符类方法:通过Firefox在我的机器上〜550ms。

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在我的机器上〜650ms。

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); 

如果你可以,并且想要对你的时间发表评论,谢谢!

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

+0

我收到了类似的结果。似乎字符类方法稍快。感谢双方的彻底答案!真的很感激它 – iali 2011-04-20 11:35:45

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

这使得*“不真实”,它将匹配尽可能少的字符。

+0

找出哪种方法更快会很有趣。 – 2011-04-19 17:46:42

+0

@Alin Purcaru:我会认为你的,因为它只对*当前*字符感兴趣。我看到你的基准似乎证实了。 – Piskvor 2011-04-19 18:04:17

+0

感谢您的支持 - 工作良好 – iali 2011-04-20 11:34:51