Wrong output using replaceall

后端 未结 4 828
误落风尘
误落风尘 2021-01-16 03:20

Why do i get \"AAAAAAAAA\" instead of \"1A234A567\" from following Code:

String myst = \"1.234.567\";

String test = myst.replaceAll(\".\", \"A\");

System.o         


        
4条回答
  •  被撕碎了的回忆
    2021-01-16 03:55

    Try this:

    String test = myst.replace(".", "A");
    

    The difference: replaceAll() interprets the pattern as a regular expression, replace() interprets it as a string literal.

    Here's the relevant source code from java.lang.String (indented and commented by me):

    public String replaceAll(String regex, String replacement) {
        return Pattern.compile(regex)
                      .matcher(this)
                      .replaceAll(replacement);
    }
    
    
    public String replace(CharSequence target, CharSequence replacement) {
        return Pattern.compile(
                  target.toString(),
                  Pattern.LITERAL /* this is the difference */
               ).matcher(this)
                .replaceAll(
                    Matcher.quoteReplacement(
                        /* replacement is also a literal,
                           not a pattern substitution */
                        replacement.toString()
                ));
    }
    

    Reference:

    • String.replaceAll(String, String)
    • String.replace(CharSequence, CharSequence)
    • Pattern.LITERAL

提交回复
热议问题