Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

java - Whats the difference between z and  in a regular expression and when and how do I use it?

From http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html:

  The end of the input but for the final terminator, if any
z  The end of the input

But what does it mean in practice? Can you give me an example when I use either the or z.

In my test I thought that "StackOverflow ".matches("StackOverflow\z") will return true and "StackOverflow ".matches("StackOverflow\Z") returns false. But actually both return false. Where is the mistake?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Even though 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 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 . When applied to this string, both ^[a-z]+$ and A[a-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 . z matches after the line break, which is not matched by the character class.

http://www.regular-expressions.info/anchors.html

The way I read this "StackOverflow ".matches("StackOverflow\z") should return false because your pattern does not include the newline.

"StackOverflow
".matches("StackOverflow\z\n") => false
"StackOverflow
".matches("StackOverflow\Z\n") => true

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...