2011-01-21 415 views
0

我正在嘗試開發一個相當快速的全文搜索。它將讀取索引,並且理想情況下應該只在一個正則表達式中運行匹配。Perl正則表達式包含多個單詞的匹配行

因此,我需要一個匹配行的正則表達式,只有當某些單詞被包含時才匹配行。

E.g. for

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

不給出結果。

總結: 我需要一個正則表達式來匹配包含多個單詞的行,並返回這些整行。

在此先感謝您的幫助!我嘗試了這麼多,但只是沒有得到它的工作。

回答

1

^$元字符默認情況下只匹配輸入的開始和結束。爲了讓他們行的開始和結束匹配,使m(多行)標誌:

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 

但是,如果你真的想要一個快速搜索,正則表達式(用很多展望未來)不是要走的路,如果你問我。

+0

但這不是想要的...... – ysth 2011-01-21 09:25:41

+0

啊,你說得對。我沒有仔細閱讀這個問題。 – 2011-01-21 09:26:32

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

所以,用而變異比變種更具有更快regexp.``