• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

validating double value using regular expression

 
HungryJavaGoat
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
HungryJavaGoat
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic