Java: Remove numbers from string

人走茶凉 提交于 2019-12-11 06:52:13

问题


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:


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();
}



回答5:


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



回答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);

}


来源:https://stackoverflow.com/questions/41505028/java-remove-numbers-from-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!