正则表达式:^和\ A之间的差异

时间:2010-10-26 04:52:34

标签: regex

^\A之间唯一的区别是\A在换行后永远无法匹配的事实? (即使在多线模式下)

The PCRE man page says:
^      assert start of string (or line, in multiline mode)
...
\A     matches at the start of the subject

谢谢!

4 个答案:

答案 0 :(得分:9)

是。 \A会在您的价值开头匹配。 ^将匹配值的开头,但也会在多线模式(//m)中的换行符后立即匹配。

\Z类似,但值的结尾。但是,它会在值结尾处的换行符之前匹配。如果您不想要此行为,请使用\z,它在值的末尾仅匹配

有用的参考:perlre manpage

答案 1 :(得分:4)

如果您将此作为目标或主题字符串:

Line 1\n
Line 2\n
Line 3\n

正则表达式/^Line/gm将匹配所有三行。如果^标志存在,则/m锚点匹配字符串的第一部分或逻辑CR / LF之后。

正则表达式/\ALine/gm只会匹配第一行,无论如何。 \A断言仅匹配目标或主题字符串的绝对开头,而不管/m标志。

答案 2 :(得分:2)

是的,根据documentation

  

\ A,\ Z和\ z断言与传统的抑扬符不同   和美元(在下一节中描述),因为它们只匹配   在主题字符串的开头和结尾,无论选项是什么   集。

答案 3 :(得分:0)

如果您阅读perldoc perlretut,这是一个对您的理解有用的摘录。

   ·   s modifier (//s): Treat string as a single long line.  '.' matches any character, even "\n".  "^" matches only at the beginning of the string
       and "$" matches only at the end or before a newline at the end.

   ·   m modifier (//m): Treat string as a set of multiple lines.  '.' matches any character except "\n".  "^" and "$" are able to match at the start
       or end of any line within the string.

   ·   both s and m modifiers (//sm): Treat string as a single long line, but detect multiple lines.  '.' matches any character, even "\n".  "^" and
       "$", however, are able to match at the start or end of any line within the string.

   Here are examples of "//s" and "//m" in action:

       $x = "There once was a girl\nWho programmed in Perl\n";

       $x =~ /^Who/;   # doesn't match, "Who" not at start of string
       $x =~ /^Who/s;  # doesn't match, "Who" not at start of string
       $x =~ /^Who/m;  # matches, "Who" at start of second line
       $x =~ /^Who/sm; # matches, "Who" at start of second line

       $x =~ /girl.Who/;   # doesn't match, "." doesn't match "\n"
       $x =~ /girl.Who/s;  # matches, "." matches "\n"
       $x =~ /girl.Who/m;  # doesn't match, "." doesn't match "\n"
       $x =~ /girl.Who/sm; # matches, "." matches "\n"

   Most of the time, the default behavior is what is wanted, but "//s" and "//m" are occasionally very useful.  If "//m" is being used, the start of
   the string can still be matched with "\A" and the end of the string can still be matched with the anchors "\Z" (matches both the end and the
   newline before, like "$"), and "\z" (matches only the end):

       $x =~ /^Who/m;   # matches, "Who" at start of second line
       $x =~ /\AWho/m;  # doesn't match, "Who" is not at start of string

       $x =~ /girl$/m;  # matches, "girl" at end of first line
       $x =~ /girl\Z/m; # doesn't match, "girl" is not at end of string

       $x =~ /Perl\Z/m; # matches, "Perl" is at newline before end
       $x =~ /Perl\z/m; # doesn't match, "Perl" is not at end of string