# Extract a number using regular expression?

H Paul
Ranch Hand
Posts: 471
4
Hi,

I have a string, for example, There are 365 days in a year on earth!
I wanted to extract the number 365.

I loop thru the string and test if a character is a digit, I concat it, so at the end I got 365.
Now, how do I do it using regular expression?

1M Thanks.

Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34669
366
\d means one digit
\d+ means one or more digits
() means capture that group

Can you build a regular expression using this information?

Jon Avadis
Ranch Hand
Posts: 49
If your String always contains only one (1) group of digits, you could approach this from the opposite end and
remove all non-digits with the Regex \D

If your look at the methods that the String class has, you'll find nice practical ones for both approaches.

Rob Spoor
Sheriff
Posts: 20546
56
Jon Avadis wrote:If your String always contains only one (1) group of digits, you could approach this from the opposite end and
remove all non-digits with the Regex \D

Which would return 1252365 for the sentence "A year has 12 months, 52 weeks and 365 days". I doubt that's what you want. The regex Jeanne was hinting at will allow you to, with a loop, get 12, 52 and 365 all separately.

Jon Avadis
Ranch Hand
Posts: 49
Rob Spoor wrote:
Jon Avadis wrote:If your String always contains only one (1) group of digits, you could approach this from the opposite end and
remove all non-digits with the Regex \D

Which would return 1252365 for the sentence "A year has 12 months, 52 weeks and 365 days". I doubt that's what you want. The regex Jeanne was hinting at will allow you to, with a loop, get 12, 52 and 365 all separately.

I fully agree that Jeanne's suggestion is more flexible.

Rob Spoor
Sheriff
Posts: 20546
56
I missed that red part

H Paul
Ranch Hand
Posts: 471
4

I'll look at the group option.

H Paul
Ranch Hand
Posts: 471
4
With group

I got
365
1

But if the text="There are 365 days on earth! from day 1. From day 1 there are 365 days.";
then with the same pattern="(\\D*)(\\d+)(\\D*) (\\d+)";

I did not get
365
1
1
365

Is there a way to change the grouping only once so that it will work dynamically for all strings? because without group like pattern="\\d+" is OK.

Maarten Bodewes
Greenhorn
Posts: 14
Try Matcher.find() multiple times using "\\d+" as input...

David Scherfgen
Greenhorn
Posts: 1
I have recently started building a website that will collect regular expressions people frequently ask for.
My first article covers the (simple) problem of matching numbers. It discusses matching integer numbers and decimal fractions (also with E notation).

The article can be found here: Regular Expression for Numbers

There's also one about IP matching with Regex.

PS: Do you like my mascot "Tyrannosaurus Regex"?