javaregexvalidationmatch

Regex to allow 1.00, .10, or 10. but not allow a single decimal


I have been trying to figure out the regular expression validation for my java program that will allow the following currency values "1", "1.00", ".1", or "1." but not a single decimal ".".

The digits before or after the decimal (if it exists) can be any length.

What I have is

(([\d]*\.)?[\d]*)

but that allows a single decimal without any numbers before or after it.


Solution

  • It should work.

    \d+\.?\d*|\d*\.?\d+
    

    DEMO

    Use String#matches() method to match it.

    sample code:

    String regex="\\d+\\.?\\d*|\\d*\\.?\\d+";
    
    System.out.println("1".matches(regex));   // true
    System.out.println("1.00".matches(regex));// true
    System.out.println(".1".matches(regex));  // true
    System.out.println("1.".matches(regex));  // true
    
    System.out.println(".".matches(regex));   // false