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

Example

Output

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

Output

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.

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 minus sign, you can include that as well in the above pattern like “[^0-9.-]”.

Output

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

Output

See Also:

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

 

Tags
Join 1000+ fellow learners! Enter your email address below: