perl非贪婪的正则表达式匹配太多了

时间:2013-08-23 01:11:19

标签: regex macos perl html-parsing

我有file类似

的内容
<post href="http://example.com/" description="Example website" tag="more text"/>

我想得到的是Example website。这样做的:

cat file | perl -pe 's/.*description=".*?"//'

按预期工作,我得到tag="more text"/>,但在尝试时:

cat file | perl -pe 's/.*description="(.*)?"/\1/'

我得到Example website" tag="more text/>,而我期待获得Example website。所以看起来有些东西的捕获和反向引用并没有按预期工作,虽然我想我可能理解为什么,但我不确定如何解决它。

我总是这样做:

cat file | perl -pe 's/.*description="//;s/".*//'

但我真的想了解如何使用正则表达式来解决它,而不是做两次替换。

2 个答案:

答案 0 :(得分:1)

你没有使用非贪婪的,你在可选的捕获组中有贪婪,因为问号就在组的末端括号后面:

变化:

description="(.*)?"

为:

description="(.*?)"

你应该得到预期的结果。

答案 1 :(得分:1)

?元字符在正则表达式中有两个含义。

当它跟随*+之类的字符,它允许表达式匹配可变次数时,它就是“非贪婪”修饰符。

.*?
a+?
(foo){3,}?               # actually, I'm not sure about this one

它 在其他情况下,它意味着“匹配0或1次”

abc?d                    # matches "abcd" or "abd"

通过将?放在捕获组之外,您已将其更改为第二个含义。把它放在捕获组内,就像@smerny说的那样。

(.*?)