2011-04-19 171 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