2010-10-26 56 views
4

^\A之间的唯一区别\A在换行符后永远不会匹配的事实吗? (即使在多线模式下)正则表达式:^和 A之间的区别

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

谢谢!

回答

8

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

\Z是相似的,但与价值的结束。不过,它会在之前匹配换行符的值。如果您不想要这种行为,请使用\z,该值在值的末尾与仅匹配

有用的参考:perlre manpage

+0

这个答案已经被添加到[堆栈溢出正则表达式常见问题解答(http://stackoverflow.com/a/22944075/2736496),在“锚”。 – aliteralmind 2014-04-10 00:21:33

2

是,根据documentation

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

4

如果您有这方面的目标或目标字符串:

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

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

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

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 
相关问题