$即使\n在匹配的字符串中有额外的尾随,行结束锚匹配,所以我们使用\Z而不是$
例如
^\w+$将匹配字符串abcd\n但^\w+\Z不匹配
怎么样\A和什么时候使用?
与任何正则表达式功能一样,当它更准确地描述您需要的内容而不是任何更通用的功能时,您就可以使用它。如果您知道要在字符串(而不是逻辑行)的开头完全匹配,请使用描述该内容的正则表达式功能。不要使用在您不想要的情况下可能匹配的正则表达式功能。
对于 Perl,有关零宽度断言的详细信息,请参阅perlre文档:
\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)
Run Code Online (Sandbox Code Playgroud)