问题
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:
The . in the second replaceAll should be escaped:
name=name.replaceAll("\\.", "");
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