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

前端 未结 6 1997
鱼传尺愫
鱼传尺愫 2020-12-01 07:27

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

\\Z  The end of the input but for the fin         


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-01 08:14

    I think the main problem here is the unexpected behavior of matches(): any match must consume the whole input string. Both of your examples fail because the regexes don't consume the linefeed at the end of the string. The anchors have nothing to do with it.

    In most languages, a regex match can occur anywhere, consuming all, some, or none of the input string. And Java has a method, Matcher#find(), that performs this traditional kind of match. However, the results are the opposite of what you said you expected:

    Pattern.compile("StackOverflow\\z").matcher("StackOverflow\n").find()  //false
    Pattern.compile("StackOverflow\\Z").matcher("StackOverflow\n").find()  //true
    

    In the first example, the \z needs to match the end of the string, but the trailing linefeed is in the way. In the second, the \Z matches before the linefeed, which is at the end of the string.

提交回复
热议问题