Java: Remove numbers from string

2019-08-02 06:40发布

问题:

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.

回答1:

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("\\+", "_");


回答2:

You don't need to escape the ^, you can use \\d+ to match multiple digits, and \\. for a literal dot and you don't need multiple calls to replaceAll. For example,

private static String removeSignsFromName(String name) {
    return name.replaceAll("^\\d+\\.", "");
}

Which I tested like

public static void main(String[] args) {
    System.out.println(removeSignsFromName("23.Piano+trompet"));
}

And got

Piano+trompet


回答3:

Two problems:

  1. The . in the second replaceAll should be escaped:

    name=name.replaceAll("\\.", "");
    
  2. The ^ in the third one should NOT be escaped:

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

Oh! and the parentheses are useless since you don't use the captured string.



回答4:

return name.replaceFirst("^\\d+\\.", "");


回答5:

How about this:

public static String removeNumOfStr(String str) {
    if (str == null) {
        return null;
    }
    char[] ch = str.toCharArray();
    int length = ch.length;
    StringBuilder sb = new StringBuilder();
    int i = 0;
    while (i < length) {
        if (Character.isDigit(ch[i])) {
            i++;
        } else {
            sb.append(ch[i]);
            i++;
        }
    }
    return sb.toString();
}


回答6:

public static void removenum(String str){

    char[] arr=str.toCharArray();
    String s="";

    for(char ch:arr){

        if(!(ch>47 & ch<57)){

            s=s+ch;
        }
            }
    System.out.println(s);

}