I'm trying to use a regular expression to validate a value for sleep entered by the user. The test should fail all negative values and 0 but let pass all combinations of + . and digits that would amount to a valid parameter for sleep.
Examples for valid: 1, 1.5, .5, 0.5, +1, +.5, +1.3 etc.
Examples for invalid: 0, .0, 0., 0.0, +0, +.0, +0, +0.0 etc. and any string starting with a -
I wrote a small program to test the regular expressions I'm using now - two expressions combined in a test statement. While looking a bit contrived they almost do the job except that strings like .1.1 still pass the test as valid.
Can someone help me take the final step?
#!/bin/bash
if [ $# -gt 0 ] ; then # user entered parameter for sleep
# check fails if it's not a positive floating point number
if ! [[ $1 =~ ^\+?\.?[0-9]+\.?[0-9]*$ ]] || [[ $1 =~ ^[\+-]?0?\.?0*$ ]]; then
echo invalid value for sleep: $1
else
echo valid: $1
fi
fi
Thanks.
------ Post updated at 01:08 PM ------
I found a solution by adding an && clause to the if condition:
if ! [[ $1 =~ ^\+?\.?[0-9]+\.?[0-9]*$ ]] || [[ $1 =~ ^[\+-]?0?\.?0*$ ]] && ! [[ $1 =~ ^\.*$ ]
but it looks even more contrived now.
Is there a way to solve the problem within one regular expression? Or something much shorter? (I'm not overly familiar with regular expressions and I expect an expert to come up easily with something shorter, humiliatingly shorter.)
------ Post updated at 01:10 PM ------
OMG. There's a ] missing at the end.