Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex on doubles

Tags:

java

regex

I'm trying to check for a double that has a maximum of 13 digits before the decimal point and the decimal point and numbers following it are optional. So the user could write a whole number or a number with decimals.

To start with I had this:

if (check.matches("[0-9](.[0-9]*)?"))

I've been through several pages on Google and haven't had any luck getting it working despite various efforts. My thought was to do it like this but it doesn't work:

[0-9]{1,13}(.[0-9]*)?

How can I do it?

like image 498
Duane Avatar asked Jan 28 '13 13:01

Duane


5 Answers

Don't forget to escape the dot.

if (check.matches("[0-9]{1,13}(\\.[0-9]*)?"))
like image 90
John Kugelman Avatar answered Nov 07 '22 15:11

John Kugelman


First of all you need to escape the dot(in java this would be [0-9]{1,13}(\\.[0-9]*)?). Second of all don't forget there is also another popular representation of doubles - scientific. So this 1.5e+4 is again a valid double number. And lastly don't forget a double number may be negative, or may not have a whole part at all. E.g. -1.3 and .56 are valid doubles.

like image 5
Ivaylo Strandjev Avatar answered Nov 07 '22 14:11

Ivaylo Strandjev


You need to escape the dot and you need at least on digit after the dot

[0-9]{1,13}(\\.[0-9]+)?

See it here on Regexr

like image 2
stema Avatar answered Nov 07 '22 13:11

stema


John's answer is close. But a '-' needs to be added, in case it's negative, if you accept negative values. So, it would be modified to -?[0-9]{1,13}(\.[0-9]*)?

like image 1
Trenton D. Adams Avatar answered Nov 07 '22 13:11

Trenton D. Adams


if you need to validate decimal with commas and negatives:

Object testObject = "-1.5";
boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject);

Good luck.

like image 1
august0490 Avatar answered Nov 07 '22 13:11

august0490