Java: removing numbers from a string

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

 private String removeSignsFromName(String name) { name = name.replaceAll(" ", ""); name = name.replaceAll(".", ""); return name.replaceAll("\\^([0-9]+)", ""); } 

But this is not so. In addition, there is no error at runtime.

+1
source share
6 answers

The following replaces all whitespace characters ( \\s ), periods ( \\. ) And digits ( \\d ) with "" :

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

What if I want to replace + with _ ?

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

You do not need to hide ^ , you can use \\d+ to match multiple digits and \\. for a literal point, and you don't need multiple calls to replaceAll . For example,

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

What I tested as

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

And received

 Piano+trompet 
+2
source

Two problems:

  • . in the second, replaceAll should be escaped:

     name=name.replaceAll("\\.", ""); 
  • In the third case ^ should not be escaped:

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

ABOUT! and parentheses are useless since you are not using a captured string.

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

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

All Articles