Perl Regex匹配包含多个单词的行

时间:2011-01-21 09:14:38

标签: regex perl

我正在努力开发一个相当快速的全文搜索。它将读取索引,理想情况下应该只在一个正则表达式中运行匹配。

因此,我需要一个只有在包含某些单词时匹配行的正则表达式。

E.g。对

my $txt="one two three four five\n".
        "two three four\n".
        "this is just a one two three test\n";

只应匹配第一行和第三行,因为第二行不包含单词“one”。

现在我可以在一段时间内浏览每一行()或使用多个正则表达式,但我需要我的解决方案才能快速。

这里的例子: 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);

没有输出。

总结: 我需要一个正则表达式来匹配包含多个单词的行,并返回这些整行。

提前感谢您的帮助!我尝试了很多,但只是不让它发挥作用。

2 个答案:

答案 0 :(得分:1)

默认情况下,^$元字符仅匹配输入的开头和结尾。要让它们匹配行的开头和结尾,请启用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

但是,如果你真的想要一个快速搜索,如果你问我,那么正则表达式(有很多展望)是不可取的。

答案 1 :(得分:0)

<强>代码:

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%            --

<强>Сonclusion

因此,使用while的变体比使用regexp的变体更快.`