2012-06-21 46 views
2

我從Jeffrey Friedl的書Mastering Regular Expressions 3rd Ed。(page 167)運行我的perl腳本時遇到以下錯誤,任何人都可以幫助我??序列(?在正則表達式中不完整 - 負查找

錯誤消息:?

序列(在正則表達式不完整的;標記爲< - 這裏以m/ ( ( (< - HERE /通過/ home/wubin28/mastering_regex_cn/p167.pl line 13.

我的perl腳本

#!/usr/bin/perl 

use 5.006; 
use strict; 
use warnings; 

my $str = "<B>Billions and <B>Zillions</B> of suns"; 

if ($str =~ m! 
    (
     <B> 
     (
      (?!<B>) ## line 13 
      . 
     )*? 
     </B> 
    ) 
    !x 
    ) { 
    print "\$1: $1\n"; #output: <B>Billions and <B>Zillions</B> 
} else { 
    print "not matched.\n"; 
} 

回答

5
您使用符號

你的錯!用於打開和關閉正則表達式,同時使用負向前視(?!。)。如果您的更改打開並關閉符號{和}或//。你的正則表達式評估罰款。

use strict; 

my $str = "<B>Billions and <B>Zillions</B> of suns"; 

if ($str =~ m/(<B>((?!<B>).)*?<\/B>)/x) { 
    print "\$1: $1\n"; #output: <B>Billions and <B>Zillions</B> 
} else { 
    print "not matched.\n"; 
} 
+0

明白了。非常感謝! –

+0

你也可以逃脫! (\!)裏面的正則表達式,如果你想使用m!句法 –