多行模式下字符串开始和结束的正则表达式

Regular expression for start and end of string in multiline mode

在正则表达式中,在多行模式下,^$分别代表行首和行尾。如何匹配整个字符串的结尾?

字符串中

Hello\nMary\nSmith\nHello\nJim\nDow

表达式

/^Hello(?:$).+?(?:$).+?$/ms

匹配 Hello\nMary\Smith

我想知道是否有一个元字符(如\ENDSTRING)匹配整个字符串的结尾,而不仅仅是行,这样

/^Hello(?:$).+?(?:$).+?\ENDSTRING/ms

将匹配 Hello\nJim\nDow。同样,元字符匹配整个字符串的开头,而不是一行。

的确有 assertions (perlre)

\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end

...
The \A and \Z are just like ^ and $, except that they won't match multiple times when the /m modifier is used, while ^ and $ will match at every internal line boundary. To match the actual end of the string and not ignore an optional trailing newline, use \z.

另见 Assertions in perlbackslash

我不确定您在所示示例中所追求的是什么,所以这是另一个示例

perl -wE'$_ = qq(one\ntwo\nthree); say for /(\w+\n\w+)\Z/m'

打印

two
three

而使用 $ 而不是 \Z 它会打印

one
two

请注意,上面的示例也会匹配 qq(one\ntwo\three\n)(带有尾随换行符),可能适合也可能不适合。请根据您的实际需要比较上述报价中的 \Z\z。感谢 ikegami 的评论。

\A\z 总是分别匹配字符串的开头和结尾。

       without /m              with /m

\A     Beginning of string     Beginning of string
^      \A                      \A|(?<=\n)

\z     End of string           End of string
\Z     \z|(?=\n\z)             \z|(?=\n\z)
$      \z|(?=\n\z)             \z|(?=\n)

换句话说,

┌─────────────────── `\A` and `^`
│     ┌───────────── `(?m:$)`
│     │ ┌─────────── `(?m:^)`
│     │ │     ┌───── `\Z` and `$`
│     │ │     │ ┌─── `\z`, `\Z` and `$`
│     │ │     │ │
F o o ␊ B a r ␊

记住,所有这些匹配都是零长度的。