我有一個非貪婪的正則表達式的問題。我已經看到有關於非貪婪的正則表達式的問題,但他們沒有回答我的問題。perl非貪婪問題
問題:我試圖匹配「哈哈」錨的href。
注:我知道這可以用Perl HTML解析模塊來完成,我的問題是不約在Perl解析HTML。我的問題是關於正則表達式本身,而HTML僅僅是一個例子。
測試用例:我有4個試驗.*?
和[^"]
。 2首先產生預期的結果。然而,第三不和第四隻是,但我不明白爲什麼。
問題:
- 爲什麼沒有第三個測試失敗在這兩個試驗
.*?
和[^"]
?不應該不貪心的操作員工作? - 爲什麼第四次測試是否在
.*?
和[^"]
的兩次測試中都有效?我不明白爲什麼在前面加入.*
會改變正則表達式。 (除了前面的.*
之外,第3次和第4次測試是相同的)。
我可能不明白這些正則表達式究竟是如何工作的。 A perl cookbook recipe提到了一些東西,但我不認爲它回答了我的問題。
use strict;
my $content=<<EOF;
<a href="/hoh/hoh/hoh/hoh/hoh" class="hoh">hoh</a>
<a href="/foo/foo/foo/foo/foo" class="foo">foo </a>
<a href="/bar/bar/bar/bar/bar" class="bar">bar</a>
<a href="/lol/lol/lol/lol/lol" class="lol">lol</a>
<a href="/koo/koo/koo/koo/koo" class="koo">koo</a>
EOF
print "| $1 | \n\nThat's ok\n" if $content =~ m~href="(.*?)"~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nThat's ok\n" if $content =~ m~href="(.*?)".*>lol~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nWhy does not the 2nd non-greedy '?' work?\n"
if $content =~ m~href="(.*?)".*?>lol~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nIt now works if I put the '.*' in the front?\n"
if $content =~ m~.*href="(.*?)".*?>lol~s ;
print "\n###################################################\n";
print "Let's try now with [^]";
print "\n###################################################\n\n";
print "| $1 | \n\nThat's ok\n" if $content =~ m~href="([^"]+?)"~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nThat's ok.\n" if $content =~ m~href="([^"]+?)".*>lol~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nThe 2nd greedy still doesn't work?\n"
if $content =~ m~href="([^"]+?)".*?>lol~s ;
print "\n---------------------------------------------------\n";
print "| $1 | \n\nNow with the '.*' in front it does.\n"
if $content =~ m~.*href="([^"]+?)".*?>lol~s ;
幽州的問題,並說有產生預期結果的解決方案。我不確定問題是什麼。 – musiKk 2011-05-14 10:00:54
你是對的,我不夠精確。我編輯並更清楚地陳述了這個問題。 – vkats 2011-05-14 10:13:27