Search code examples
javaregexstringreplaceall

Why does replaceAll remove the numbers from the String?


String foo = "a3#4#b";
String afterPunctutationRemoval = foo.replaceAll("[,.;:?!'-_\"/()\\{}]", "");
System.out.println(afterPunctutationRemoval);

it gives me "a##b" as a result, can someone explain me why?

Shouldn't it return the string as it is?


Solution

  • Your character class contains the range '.._ which matches digits as well.

    Put the - at the start or end of the character class:

    foo.replaceAll("[,.;:?!'_\"/()\\{}-]", "")
    

    or escape it:

    foo.replaceAll("[,.;:?!'\\-_\"/()\\{}]", "");