Search code examples
javaregexstringreplaceall

Java: Remove numbers from string


I have a string like 23.Piano+trompet, and i wanted to remove the 23. part from the string using this function:

private String removeSignsFromName(String name) {
    name = name.replaceAll(" ", "");
    name = name.replaceAll(".", "");

    return name.replaceAll("\\^([0-9]+)", "");
}

But it doesn't do it. Also, there is no error in runtime.


Solution

  • The following replaces all whitespace characters (\\s), dots (\\.), and digits (\\d) with "":

    name.replaceAll("^[\\s\\.\\d]+", "");
    

    what if I want to replace the + with _?

    name.replaceAll("^[\\s\\.\\d]+", "").replaceAll("\\+", "_");