Java: Remove numbers from string
Asked Answered
B

6

1

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.

Basement answered 6/1, 2017 at 11:45 Comment(2)
You escape the ^, so it searches for a literal ^, which is not present.Savill
. matches any character and replaceAll() replaces all the characters. Escape the dot "\\."Libel
M
3

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("\\+", "_");
Manhunt answered 6/1, 2017 at 11:49 Comment(0)
E
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
Elsey answered 6/1, 2017 at 11:48 Comment(1)
he needs the ^, if he want to make sure the replacement can only occur on the beginning of string. however he should not escape the ^ Your pattern will replace all number + dots in the text, don't know if it is desired. Also, what for the grouping, it makes no sense, does it?Varia
E
1

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.

Evy answered 6/1, 2017 at 11:53 Comment(0)
S
1

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();
}
Spotter answered 12/7, 2019 at 4:40 Comment(0)
V
0
return name.replaceFirst("^\\d+\\.", "");
Varia answered 6/1, 2017 at 11:52 Comment(0)
F
-1
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);

}
Fanlight answered 18/11, 2018 at 7:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.