2

下面是我正在玩的一个脚本。使用下面的脚本将打印a

$tmp = "cd abc/test/.";
if ( $tmp =~ /cd ([\w\/\.])/ ) {
   print $1."\n";
}

但是,如果我将其更改为:

$tmp = "cd abc/test/.";
if ( $tmp =~ /cd ([\w\/\.]+)/ ) {
   print $1."\n";
}

然后打印:cd abc/test/.

据我了解,+ 匹配一个或多个匹配序列,如果我错了,请纠正我。但是为什么在第一种情况下它只匹配a?我认为它不应该匹配任何东西!

谢谢你。

4

2 回答 2

3

在正则表达式中,括号中的字符仅计算给定括号内的一个字符的匹配。换句话说,[\w\/\.]完全匹配以下字符之一:

  1. 一个字母数字字符或"_"(the \w)。
  2. 正斜杠(\/--notice 需要转义正斜杠,因为它用作正则表达式开头和结尾的默认标记)
  3. 句点(\.--再次转义,因为.表示除换行符之外的任何字符)。

因为/cd ([\w\/\.])./只将一个字符捕获到$1中,所以它会捕获第一个字符,在这种情况下是"a".

您是正确的,因为+允许匹配一个或多个此类字符。由于正则表达式默认情况下会贪婪匹配,因此您应该在第二次匹配中获得所有"abc/test/."for $1

如果您还没有这样做,您可能需要仔细阅读perldoc perlretut.

于 2011-11-07T17:22:22.087 回答
3

你是对的。在第一种情况下,您匹配该字符类中的单个字符,而在第二种情况下,您匹配至少一个字符,并在第一个字符之后匹配尽可能多的字符。

第一 :

"
cd\            # Match the characters “cd ” literally
(              # Match the regular expression below and capture its match into backreference number 1
   [\w\/\.]       # Match a single character present in the list below
                     # A word character (letters, digits, etc.)
                     # A / character
                     # A . character
)
"

第二个 :

"
cd\            # Match the characters “cd ” literally
(              # Match the regular expression below and capture its match into backreference number 1
   [\w\/\.]       # Match a single character present in the list below
                     # A word character (letters, digits, etc.)
                     # A / character
                     # A . character
      +              # Between one and unlimited times, as many times as possible, giving back as needed (greedy)
)
"
于 2011-11-07T17:22:50.363 回答