I need to match regex to value that is numeric with decimal. Currently I have /^-?[0-9]\d*(.\d+)/ but it does not account for .00 How would I fix that
Current Valid:
1
1.0
1.33
.00
Current Invalid:
Alpha Character
You need to handle the two possibilities (numbers without a decimal part and numbers without an integer part):
/\A-?(?:\d+(?:\.\d*)?|\.\d+)\z/
#^ ^ ^ ^^ ^---- end of the string
#| | | |'---- without integer part
#| | | '---- OR
#| | '---- with an optional decimal part
#| '---- non-capturing group
#'---- start of the string
or make all optional and ensure there's at least one digit:
/\A-?+(?=.??\d)\d*\.?\d*\z/
# ^ ^ ^ ^---- optional dot
# | | '---- optional char (non-greedy)
# | '---- lookahead assertion: means "this position is followed by"
# '---- optional "-" (possessive)
Note: I used the non-greedy quantifier ??
only because I believe that numbers with integer part are more frequent, but it can be a false assumption. In this case change it to a greedy quantifier ?
. (whatever the kind of quantifier you use for the "unknow char" it doesn't matter, this will not change the result.)
If the first part is optional you can mark it off as such with `(?:...)?:
/\A(?:-?[0-9]\d*)?(.\d+)/
The ?:
beginning means this is a non-capturing group so it won't interfere with the part you're trying to snag.
What about simple: /\d*\.?\d*/
?
Create a regex with the variants you want to match, in this case, 3:
N
N.NN
.NN
i.e.:
(\d+\.\d+|\d+|\.\d+)
regex 101 Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With