Skip to main content

Java: Numbers only String by removing non numeric characters

With Java, deleting non numeric characters (letters, symbols etc) from a string to produce a numbers-only String is a common requirement in web applications, as application users are used to insert numeric values with non-numeric characters.

For example a phone number will be entered with (-) characters like;
A price value may be entered with (,) characters like;

In Java, java.lang.Character class has a method; isDigit() which can be used to identify whether a character is a digit or not. Following method can be used for extracting a numbers-only string.

public static String getOnlyNumerics(String str) {

if (str == null) {
return null;

StringBuffer strBuff = new StringBuffer();
char c;

for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);

if (Character.isDigit(c)) {
return strBuff.toString();

Calling above method with any String will return a numbers-only string.


  1. Thanks for pointing me to the isDigit() method, I hadn't used it before.

  2. Ado marune .. wade wenawa thnx!!!

  3. Thanks for code snippet

  4. Gracias por el método!
    Pura vida!

  5. One could also use regular expressions to form...

    public static String getOnlyNumerics(String str) {
    return str.replaceAll( "\\D", "" );

    /Michael H

  6. String result = yourString.replaceAll( "[^\\d]", "" );


Post a Comment

We appreciate your opinions, suggestions and criticism.

Popular posts from this blog

Web Services with Apache Axis 1.4 Tutorial: server and client sides

Java Sorting: Comparator vs Comparable Tutorial

Creative Commons License Digizol by Kamal Mettananda is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License .
URL of this page must be supplied in attribution
© 2004-2017