Java String Handling RegEx

Java String keep only numbers example

Java String keep only numbers example shows how to keep only numbers in String. 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 non all numeric characters from the string. This can be done using regular expression and replaceAll method of String class.

How to keep only number in String using regular expression?

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



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


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


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.


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”.


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


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


See Also:

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


About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *