1

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

String myst = "1.234.567";

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

System.out.println(test);

Any Idea?

1

4 Answers 4

7

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:

Sign up to request clarification or add additional context in comments.

Comments

6

replaceAll function take a regular expression as parameter. And the regular expression "." means "any character". You have to escape it to specify that it is the character you want : replaceAll("\\.", "A")

Comments

1

You need to escape .

make it

String myst = "1.234.567";

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

System.out.println(test);

Comments

0

Because every single char of the input matches the regexp pattern (.). To replace dots, use this pattern: \. (or as a Java String: "\\.").

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.