Java String Handling RegEx

Check if String contains number example

This Java example shows how to check if String contains number. This example also shows how to check if string contains number using regular expression as well as using other methods.

How to check if String contains number in Java?

There are several methods using which you can check if the String contains number.

1) Using Double wrapper class

Use parseDouble method of Double wrapper class to check if the String contains a valid number. If the String does not contain a number, parseDobule method throws NumberFormatException which you can catch to do further processing.

Example

Output

2) Using Apache Commons Library

If you have Apache Commons library, you can use isNumber static method of NumberUtils class to check if the String contains a valid number as given below.

This method returns true if the String contains valid Java number, false otherwise.

Output

Note:

As you may have observed, isNumber method returns false for “+12.32” value. Use this approach only if you do not expect such String in the input values.

3) Using regular expression

You can also use regular expression to check if the String contains a valid number or not as given below.

“\\d” denotes a digit in regular expression. Our pattern “\\d+” means “one or more digits”. You can also use “[0-9]+” pattern instead of “\\d+”.

Output

Note:

This pattern does not work for anything except for positive integers (and that too without the “+” sign). Use this only if it fits the requirements.

Let’s create a bit more accommodative pattern to include floating point and negative numbers.

Our original pattern was “\\d+” which checked only for one or more digits. Now we are going to include minus sign “-” which should be optional, as well as the optional dot “.” for floating point numbers. Here is the updated regular expression pattern.

Let’s test it out using same input values

Output

Looks like we have covered almost all the possible input values except for “+12.32” which gave us false while still being a valid number. We also want to add optional plus sign “+” at the beginning. Remember, valid number contains either “-” or “+” sign. Both of them cannot appear together. Here is the final version of the pattern.

We have modified the first part from “-?” to “(-|\\+)?”. Basically we grouped them together and applied “or” operator “|” so that it looks for zero or more minus sign or plus sign.

Output

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

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

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 *