Suroko
Suroko

Reputation: 105

Match number with unlimited decimal places

I want to check if a user input is a valid double number (X.XXXXX).

This is my code:

if(textField.getText().matches("^[0-9][.]+[0-9]$"))
{
    System.out.println("This is a double");
}

If the user inputs 5.5, println gets executed. If user inputs 5.55 or a number with more numbers after the dot (5.5XXX...) it will not match.

How can I define a regex that matches all numbers after the dot, no matter how many?

Upvotes: 0

Views: 289

Answers (3)

Diego Martinoia
Diego Martinoia

Reputation: 4662

Others have already mentioned regex solutions (Danyal's seems the most comprehensive so far). The "real" regex for a double is quite complicated! See this question here:

Related question on SO

But I think you are asking the wrong question (none still addresses scientific notation though):

What you want to achieve is answering "Is this string a double?". Now there are things that are far more readable and overall "better" than a regex for that.

For example, as mentioned in the comments, you can actually try to parse the string and see if it fails to be parsed. This is also the recommended approach in the question I linked, and the one you should follow.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Your plus + is misplaced:

^[0-9][.]+[0-9]$

lets users enter

5......1

You need to move it to the end:

[0-9][.][0-9]+

Anchor tags are not necessary because you are using matches().

Note that this regex is overly simplistic, because it does not support negative numbers, forces users to enter .0 for whole numbers, and does not allow scientific notation, among other things. A regex that supports these features is much more complex (see this Q&A for an example). You would be better off using a built-in parsing method to check if the input is valid or not.

Upvotes: 2

Martin Gardener
Martin Gardener

Reputation: 1001

This is your regex:

[+-]([0-9]*[.])?[0-9]+

This will accept

  • 123
  • 456.789
  • .555 and so on..

Upvotes: 0

Related Questions