正则表达式:^和\A的区别

5
< p > ^\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个回答

10

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

\Z与之类似,但位于值的结尾。然而,它还会在值的结尾处的换行符之前匹配。如果您不希望这种行为,请使用\z,它只会在值的结尾处匹配。

有用的参考资料:perlre manpage


此答案已添加到Stack Overflow正则表达式FAQ,位于“锚点”下。 - aliteralmind

4
如果您的目标或主题字符串如下所示:
Line 1\n
Line 2\n
Line 3\n

正则表达式 /^Line/gm 将匹配所有三行。当 /m 标志存在时,^锚点将匹配字符串的第一部分或逻辑CR / LF之后。
正则表达式 /\ALine/gm 只会匹配第一行。无论 /m 标志如何,\A 断言只会匹配目标字符串或主题字符串的绝对开头。

2

是的,根据文档

\A、\Z和\z断言与传统的插入符号和美元符号(在下一节中描述)不同,因为它们仅在主题字符串的开头和结尾处匹配,无论设置了哪些选项。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接