Skip to content

Java RegEx – Extract Numbers from String

Java RegEx – Extract Numbers from String example shows how to extract numbers from string using Java regex. It also shows how to extract negative and decimal numbers using regex.

How to extract numbers from a string using regex in Java?

Extracting all numeric data from the string content is a very common and useful scenerio and can be achieved using a regex pattern. The basic pattern we need to use is a “[0-9]”, i.e. character class of digits from 0 to 9. It can also be written as “\d” and means the same.

Now since the numbers can be more than 1 in length, we are going to append “+” at the end of the pattern to match the digits more than 1 in length. Here is the full regex pattern.

Where,

Let’s try this out.

Output

The above-given pattern does not work for the negative numbers. In order to do that, we need to include the minus sign in the pattern. However, it should be optional as only negative numbers have it at the start. Here is the updated regex pattern.

Where,

Let’s see an example of that.

Output

How to extract decimal numbers?

The above-given pattern does not include decimal numbers. In order to include that as well, we are going to use the below-given pattern.

Where,

Here we have specified the dot and fraction number inside a group that as a whole may appear zero or one time. Let’s try to extract numbers using this pattern.

Output

As you can see from the output, the pattern extracted positive, negative, and decimal numbers from the string.

How to extract a specific number from the string?

The above example shows how to extract all numeric data from the string. But what if you want to extract a specific number from the string? Well, in that case, you can define that specific number in a regex group and extract it using the group number as given below.

Output

If you want to learn more about the regex, please visit the 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.