Search code examples
regexpcre

Match decimal numbers


I would like to match decimal numbers like:

0.0
0.12
1.00
1.12
-0.123
-1.000
-1.123

without matching negative zeros: -0.0 or -0.00, -0.000 etc.

I have no idea how to extend the /^-?[0-9]+\.[0-9]+$/ regex to not to allow negative zeros.

UPDATE:

  • No leading zeros allowed: 01.1 or -01.1
  • Whole and fractional characters are required (.5 or 5. not allowed)

Solution

  • IIUC, you just need to add a negative lookahead (?!-0\.0+$):

    ^(?!-0\.0+$)-?\d+\.\d+$
    

    Example:

    echo '0.0
    0.12
    1.00
    1.12
    -0.123
    -1.000
    -1.123
    -0.00
    -0.0
    -0.000010
    -12.34
    ' | perl -lne 'print if /^(?!-0\.0+$)-?\d+\.\d+$/'
    #0.0
    #0.12
    #1.00
    #1.12
    #-0.123
    #-1.000
    #-1.123
    #-0.000010
    #-12.34