Saturday, February 16, 2013

Validate double values with Java regular expression


The following are Java Regular expressions for decimal numbers, integers, and double values :

String regexDecimal = "^-?\\d*\\.\\d+$";
String regexInteger = "^-?\\d+$";
String regexDouble = regexDecimal + "|" + regexInteger;


Analysis:

^: Matches the beginning position of the string
-: The minus character
?: Indicates that there is zero or one of the preceding element

The double value can be positive or negative, so the string can have one or no minus character in the beginning.

\\d: Digits; [0-9] is an alternative
*: Matches the preceding element zero or more times.

Because ".1515674" is also a valid double value, \\d in the regexDecimal is succeeded by * instead of +.

\\.: The '.' character.

Since a '.' alone matches any single character in regular expression, so an escape character \\ should be added before '.' in order to successfully represent the dot character.

+: Matches the preceding element one or more times.

Since "234." is not a valid decimal number but "234.0" is, "\\.\\d" is succeeded by + instead of *.

$: Matches the ending position of the string

|: The alternation operator

regexDouble = regexDecimal + "|" + regexInteger means that if a string either matches either the integer pattern or the decimal value pattern, then it is a double value.



import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegularExpressionTest {
 
 public static void main(String[] args) {
  
  String testString = " .4534 ";
  testString = testString.trim();
  
  String regexDecimal = "^-?\\d*\\.\\d+$";
  String regexInteger = "^-?\\d+$";
  String regexDouble = regexDecimal + "|" + regexInteger;

  Pattern pattern = Pattern.compile(regexDouble);
  Matcher matcher = pattern.matcher(testString);
  System.out.println(matcher.find());

 }
}

4 comments:

  1. This helped me in homework in Java. Thanks a lot!

    ReplyDelete
  2. I prefer this with commas and negative decimals:
    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);

    ReplyDelete
  3. Thanks very much resolved in seconds

    ReplyDelete