Invalid output using replaceall

Why am I getting "AAAAAAAAA" instead of "1A234A567" from the following code:

String myst = "1.234.567";

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

System.out.println(test);

Any idea?

+1
source share
4 answers

replaceAllthe function takes a regular expression as a parameter. And the regex "." means "any character". You must run away from it to indicate that this is the character you want:replaceAll("\\.", "A")

+6
source

Try the following:

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

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

Here's the corresponding 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:

+6
source

.

String myst = "1.234.567";

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

System.out.println(test);
+1

Since every single input char matches a regex pattern ( .). To replace the dots, use this pattern: \.(or as a Java string:) "\\.".

0
source

All Articles