[英]Perl Regex match lines that contain multiple words
我正在尝试开发一个相当快速的全文搜索。 它将读取索引,并且理想情况下应该只在一个正则表达式中运行匹配。
因此,我需要一个仅在包含某些单词时才匹配行的正则表达式。
例如
my $txt="one two three four five\n".
"two three four\n".
"this is just a one two three test\n";
仅第一行和第三行应匹配,因为第二行不包含单词“ one”。
现在,我可以在while()中遍历每一行或使用多个正则表达式,但是我需要我的解决方案要快速。
来自此处的示例: http : //www.regular-expressions.info/completelines.html (“查找包含或不包含某些单词的行”)
是我所需要的 但是,我无法在Perl中使用它。 我做了很多尝试,但都没有结果。
my $txt="one two three four five\ntwo three four\nthis is just a one two three test\n";
my @matches=($txt=~/^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$/gi);
print join("\n",@matches);
没有输出。
总结:我需要一个正则表达式来匹配包含多个单词的行,并返回这些整行。
在此先感谢您的帮助! 我做了很多尝试,但只是不起作用。
默认情况下, ^
和$
元字符仅匹配输入的开头和结尾。 为了使它们与行的开头和结尾匹配,请启用m
(MULTI-LINE)标志:
my $txt="one two three four five\ntwo three four\nthis is just a one two three test\n";
my @matches=($txt=~/^(?=.*?\bone\b)(?=.*?\btwo\b)(?=.*?\bthree\b).*$/gim);
print join("\n",@matches);
产生:
one two three four five
this is just a one two three test
但是,如果您真的想快速搜索,请问我,正则表达式(前瞻性强)不是走的路。
码:
use 5.012;
use Benchmark qw(cmpthese);
use Data::Dump;
use once;
our $str = <<STR;
one thing
another two
three to go
no war
alone in the dark
war never changes
STR
our @words = qw(one war two);
cmpthese(100000, {
'regexp with o' => sub {
my @m;
my $words = join '|', @words;
@m = $str =~ /(?!.*?\b(?:$words)\b)^(.*)$/omg;
ONCE { say 'regexp with o:'; dd @m }
},
'regexp' => sub {
my @m;
@m = $str =~ /(?!.*?\b(?:@{ [ join '|', @words ] })\b)^(.*)$/mg;
ONCE { say 'regexp:'; dd @m }
},
'while' => sub {
my @m;
@m = grep $_ !~ /\b(?:@{ [ join '|',@words ] })\b/,(split /\n/,$str);
ONCE { say 'while:'; dd @m }
},
'while with o' => sub {
my @m;
my $words = join '|',@words;
@m = grep $_ !~ /\b(?:$words)\b/o,(split /\n/,$str);
ONCE { say 'while with o:'; dd @m }
}
})
结果:
regexp:
("three to go", "alone in the dark")
regexp with o:
("three to go", "alone in the dark")
while:
("three to go", "alone in the dark")
while with o:
("three to go", "alone in the dark")
Rate regexp regexp with o while while with o
regexp 19736/s -- -2% -40% -60%
regexp with o 20133/s 2% -- -38% -59%
while 32733/s 66% 63% -- -33%
while with o 48948/s 148% 143% 50% --
包容性
因此,带有while的变体比带有regexp的变体更快。''
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.