来自 http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html :
\Z The end of the input but for the final terminator, if any
\z The end of the input
但这在实践中意味着什么?当我使用\Z 或\z 时,你能举个例子吗?
在我的测试中,我认为 "StackOverflow\n".matches("StackOverflow\\z")
将返回 true 并且 "StackOverflow\n".matches("StackOverflow\\Z")
返回 false。但实际上两者都返回错误。哪里错了?
最佳答案
Even though
\Z
and$
only match at the end of the string (when the option for the caret and dollar to match at embedded line breaks is off), there is one exception. If the string ends with a line break, then\Z
and$
will match at the position before that line break, rather than at the very end of the string.This "enhancement" was introduced by Perl, and is copied by many regex flavors, including Java, .NET and PCRE. In Perl, when reading a line from a file, the resulting string will end with a line break. Reading a line from a file with the text "joe" results in the string joe\n. When applied to this string, both
^[a-z]+$
and\A[a-z]+\Z
will match "joe".If you only want a match at the absolute very end of the string, use
\z
(lower case z instead of upper case Z).\A[a-z]+\z
does not match joe\n.\z
matches after the line break, which is not matched by the character class.
http://www.regular-expressions.info/anchors.html
我阅读此 "StackOverflow\n".matches("StackOverflow\\z")
的方式应该返回 false,因为您的模式不包含换行符。
"StackOverflow\n".matches("StackOverflow\\z\\n") => false
"StackOverflow\n".matches("StackOverflow\\Z\\n") => true
关于java - 正则表达式中的\z 和\Z 有什么区别,何时以及如何使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2707870/