End of line anchor $
match even there is extra trailing \\n
in matched string, so we use \\Z
instead of $
For example
As with any regex feature, you use it when it more exactly describes what you need as opposed to any more general feature. If you know that you want to match exactly at the start of a string (instead of logical lines), use the regex feature that describes that. Don't use regex features that could possibly match in situations that you don't want.
For Perl, see the perlre docs for details about the zero-width assertions:
\b Match a word boundary
\B Match except at a word boundary
\A Match only at beginning of string
\Z Match only at end of string, or before newline at the end
\z Match only at end of string
\G Match only at pos() (e.g. at the end-of-match position
of prior m//g)