Skip to content

Check if String contains number example

This Java example shows how to check if a string contains number using the Double class, regular expression, and apache commons library.

How to check if a string contains a number in Java?

1) Check if a string contains a number using the Double wrapper class

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

Example

Output

2) Using Apache Commons Library

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

This method returns true if the string contains a valid number, false otherwise.

Output

Note: As you may have observed, the 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 a regular expression

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

The “\\d” pattern denotes a digit in regular expression. Our pattern “\\d+” means “one or more digits”. You can also use the “[0-9]+” pattern instead of the “\\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 the 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 the 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, a 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

This example is a part of the Java String 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.