how to remove all non digit characters from a string Java
–OLD VERSION–
This is a very simple snippet method in Java to remove all non digits characters in a String. I will show you the simple method that you can use to acsomplish this, and a complete exampls so you can test the method.
Here it is the method to remove the non digits in a String.
public static String removeNonDigits(String text) {
int length = text.length();
StringBuffer buffer = new StringBuffer(length);
for(int i = 0; i < length; i++) {
char ch = text.charAt(i);
if (Character.isDigit(ch)) {
buffer.append(ch);
}
}
return buffer.toString();
}
And here is the complete example so you can try it , and see the result.
/*
* Simple example to remove all non digits characters
* in a String Text.
*
*/
/**
*
* @author neozilon
*/
public class Main {
public static String removeNonDigits(String text) {
int length = text.length();
StringBuffer buffer = new StringBuffer(length);
for(int i = 0; i < length; i++) {
char ch = text.charAt(i);
if (Character.isDigit(ch)) {
buffer.append(ch);
}
}
return buffer.toString();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String testText = "Hello 1To2The3 Wor3ld from Guate4mala5";
System.out.println("Response: " + Main.removeNonDigits(testText));
}
}
–UPDATED–
There is simpler way to do this using Regular expressions , thanks to JeeBee for the update.
// do it in just one line of code String num = text.replaceAll(”[^\\d]“, “”); // it is simple
this simple line , which replace all the non numeric character and replace it with by nothing “” , what the regular expression is doing is that
\\d means numbers from 0-9 in Regular expressions and the character ^ inside the [ ] means negation , so it is a simplear and the best way to replace the non digits character in Java.
I hope this snippet will be useful to you, thanks.
November 16th, 2009 at 12:36 pm
or …
String num = text.replaceAll(“[^\\d]“, “”);
February 7th, 2011 at 5:08 am
Thanks! it helped me very much!
April 14th, 2011 at 4:37 am
If you’re using it to put in a DB you might want to do this after the regex:
//This will insure that you have a proper int
while(num .startsWith(“0″) && num.length() > 1){//loop through the string and make sure it doesn’t start with a 0
num = num .substring(1, num .length());
}
//Then you can do.
Integer.valueOf(num);