Search code examples
javastringreplaceall

Strange behaviour for String.replaceAll() with number string


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?


Solution

  • 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(".", "");.