| Subcribe via RSS

how to remove all non digit characters from a string Java

July 10th, 2009 Posted in 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.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Furl
  • Slashdot
  • Technorati
  • TwitThis
Tags:

3 Responses to “how to remove all non digit characters from a string Java”

  1. JeeBee Says:

    or …

    String num = text.replaceAll(“[^\\d]“, “”);


  2. Dmitry Says:

    Thanks! it helped me very much! :)


  3. Killafo Says:

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


Leave a Reply