-3
String pre = "895";
System.out.println(pre);
pre = pre.replaceAll(".", "");
System.out.println(pre);

The output strangely is:

895

So all numbers are erased from the string. Why is this?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Thieri
  • 203
  • 1
  • 10
  • 2
    replaceAll takes regex as first parameter, so '.' is any character – Boris Chistov Jul 06 '20 at 13:01
  • 2
    What do you think should happen instead? Which part of *documentation* of `replaceAll` makes you think so? – Pshemo Jul 06 '20 at 13:01
  • 1
    What did you expect it to output? – Sweeper Jul 06 '20 at 13:02
  • 2
    From the [javadoc](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html): Replaces each substring of this string that matches the given **regular expression** with the given replacement. Simply use `pre.replace(".", "")` if you don't want to use regex – Lino Jul 06 '20 at 13:02
  • 1
    ReplaceAll() is unappropriate in this case because it is a regEx. – Dennis Kozevnikoff Jul 06 '20 at 13:04
  • 1
    It is time for you to **learn regex**, and one of the very first thing any regex tutorial will teach you, is that `.` period is a meta-character matching anything (except line separators). To fix, escape the character, which needs double-escaping in a Java string literal, i.e. `replaceAll("\\.", "")`, or ask the system to do it, i.e. `replaceAll(Pattern.quote("."), "")`, or don't use regex version, i.e. `replace(".", "")`. – Andreas Jul 06 '20 at 13:04
  • 2
    Did you read the _javadoc_ for method `replaceAll()`? If you did then did you understand it? Your question, in my opinion, is a RTFM. – Abra Jul 06 '20 at 13:06

1 Answers1

2

The problem here is, that the replaceAll method uses REGEX as first parameter. In REGEX . means any character so currently you are replacing any character with "". Thats the reason why your result is empty. If you want to replace with a specific character you should use pre.replace(".", "");.

Max
  • 84
  • 6