aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes validating double value using regular expression Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "validating double value using regular expression" Watch "validating double value using regular expression" New topic
Author

validating double value using regular expression

HungryJavaGoat
Greenhorn

Joined: Jun 30, 2006
Posts: 23
Hi,
How can we validate a double value with regular expression in java?
For example ..if a field takes ###.### as mask ..
then user can enter atmost 3 digits before the decimal and one decimal point followed by atmost 3 digits.
thanks for the guidance in advance..
Javier Sanchez Cerrillo
Ranch Hand

Joined: Aug 02, 2006
Posts: 152
System.out.println("333.322".matches("\\d{1,3}\\.\\d{1,3}"));


The previous expression matches:

1.- 1 to 3 digits before the decimal point
2.- A decimal point
3.- 1 to 3 digits after the decimal point


SCJP 5.0 95%<br /> <br />The greatest enemy of knowledge is not ignorance, it is the illusion of knowledge.
HungryJavaGoat
Greenhorn

Joined: Jun 30, 2006
Posts: 23
Hi ,
Thanks for your suggestion ..

but he can also enter a number without decimal which is a valid one.
example:
##.##
following are valid:
1
11
11.0
11.02
.0
.01
11.11


Following are invalid
111.00 (exceeds the number of digits before decimal)
11. (invalid if "." is present then there should be atleast one digit followed by that)
11.001 (Invalid. exceeds .number of digits after decimal point)

i want to make one regular expression which will match all the conditions to tell me whether the double entered is valid double and its matching my constraints. Thanks in advance.
Javier Sanchez Cerrillo
Ranch Hand

Joined: Aug 02, 2006
Posts: 152
Let me notice you changed the mask from ###.### to ##.##
You can express that change inside the {0,here} boundaries

//Accept Decimals
String regexDecimal = "\\d{0,2}\\.\\d{1,2}";

//Accept Integers
String regexInteger = "\\d+";

System.out.println("11.".matches(regexDecimal + "|" + regexInteger));

Let me know if this works for you.

By the way, let me recommend you the book:
Java Regular Expressions Taming the java.util.regex package

If you need to parse a lot of numeric expressions, I recommend you the library:
Java Math Expression Parser (JEP)

Which is free
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: validating double value using regular expression