gpt4 book ai didi

regex - Javascript正则表达式匹配语句

转载 作者:行者123 更新时间:2023-12-01 13:01:28 26 4
gpt4 key购买 nike

我有以下示例段落:

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.

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

My introductory line of text is the this, that and the other.

我的代码是:

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

但这会获取所有 文本。我将如何捕获直到第一个句号?

最佳答案

注意区别:

(\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 ~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);

如果可以并且愿意,请对您的时间发表评论。谢谢!

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

关于regex - Javascript正则表达式匹配语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5716938/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com