我遇到了一个非贪婪正则表达式(regex)的问题。我看到有关非贪婪正则表达式的问题,但它们并没有回答我的问题。
问题: 我正在尝试匹配“lol”锚点的href。
注意: 我知道可以使用Perl HTML解析模块来完成此操作,但我的问题与在Perl中解析HTML无关。我的问题是关于正则表达式本身的,而HTML只是一个例子。
测试用例: 我对.*?
和[^"]
进行了四个测试。前两个产生了预期的结果。然而第三个测试失败了,第四个测试成功了,但我不明白为什么。
- 为什么第三个测试在
.*?
和[^"]
的两个测试中都失败了?非贪婪运算符不应该起作用吗? - 为什么第四个测试在
.*?
和[^"]
的两个测试中都成功了?我不明白为什么在前面包含一个.*
会改变正则表达式(第三个和第四个测试相同,除了前面的.*
)。
我可能不完全理解这些正则表达式的工作原理。一个Perl Cookbook的配方提到了一些内容,但我认为它没有回答我的问题。
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 ;