Skip to content

Java String keep only numbers example

Java String keep only numbers example shows how to keep only numbers in String. The example also shows how to remove all non-numeric characters from String in Java.

How to keep only numbers in String?

Many times string contains numbers and letters and you want to keep only numbers by removing the non-numeric characters from the string. This can be done using the regular expression and the  replaceAll method of String class.

How to keep only numbers in String using regular expression?

Non-numeric characters can be removed from String using several regular expression patterns. We are going to use the “[^0-9]” pattern to match non-numeric characters and replace all of them with the empty string, where

Example

Output

You can also use the “\\d” pattern instead of the [0-9] to denote a digit in regular expression as given below. So our pattern will be “[^\\d]” which means “not a digit”.

Output

If you do not want to use the “^”, you can use the “\\D” pattern which is the exact opposite of the “\\d” and means “all non-digit characters” as given below.

Output

How to keep decimal and minus sign while removing non-numeric characters from the String?

What happens when we apply any of the above given patterns to a String containing a decimal or negative number? Let’s see.

Output

That gave us the wrong result. Along with the digits, we also need to keep the decimal point in our String. Therefore, our modified pattern will look like “[^0-9.]” which means “not a digit or not decimal”.

Output

If you also want to keep the minus sign, you can include that as well in the above pattern like “[^0-9.-]”.

Output

The same can be applied to extract the phone number from String as given in the below example.

Output

See Also:

This example is a part of the Java String tutorial and Java RegEx tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.