【发布时间】:2011-08-25 10:36:30
【问题描述】:
我遇到了非贪婪正则表达式 (regex) 的问题。我看到有关于非贪婪正则表达式的问题,但他们没有回答我的问题。
问题:我正在尝试匹配“lol”锚点的 href。
注意:我知道这可以通过 Perl HTML 解析模块来完成,我的问题是不是关于在 Perl 中解析 HTML。我的问题是关于正则表达式本身,而 HTML 只是一个例子。
测试用例:我对@987654322@ 和[^"] 有四个测试。两者首先产生了预期的结果。但是第三个没有,第四个只是,但我不明白为什么。
-
为什么第三个测试在
.*?和[^"]的两个测试中都失败了?非贪婪的算子不应该工作吗? -
为什么第四个测试在
.*?和[^"]的两个测试中都有效?我不明白为什么在前面包含.*会改变正则表达式(第三和第四个测试是相同的,除了前面的.*)。
我可能不完全理解这些正则表达式是如何工作的。 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 ;
【问题讨论】:
-
你陈述了一个问题,并说有一个产生预期结果的解决方案。我不确定问题是什么。
-
你说得对,我不够精确。我更清楚地编辑并陈述了这个问题。
标签: regex perl non-greedy regex-greedy