ImagineDragon
ImagineDragon

Reputation: 307

Strange regular expression behaviour for decimal numbers in java

The following is my java code

Pattern p = Pattern.compile("-?\\d*\\.?\\d*");
Matcher m = p.matcher("the numbers are -3.4 and 132");
while (m.find()) {
    System.out.println(m.group());
}

But it fails to match either number. Can anyone shed some light upon this program?

Upvotes: 0

Views: 69

Answers (2)

sp00m
sp00m

Reputation: 48817

Your regex matches the numbers, but also every inter-char. Use \\d+ instead of your second \\d* for example.

I usually use the following regex to match numbers (already escaped for Java):

[-+]?\\d*[.]?\\d+(?:[eE][-+]?\\d+)?

Upvotes: 4

Toto
Toto

Reputation: 91385

Use this regex:

-?\\d+(?:\\.\\d+)?

Upvotes: 2

Related Questions