Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match regex with numeric value and decimal

Tags:

regex

ruby

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 
like image 631
Aziz Avatar asked Apr 29 '16 19:04

Aziz


4 Answers

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.)

like image 192
Casimir et Hippolyte Avatar answered Oct 18 '22 18:10

Casimir et Hippolyte


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.

like image 1
tadman Avatar answered Oct 18 '22 18:10

tadman


What about simple: /\d*\.?\d*/ ?

like image 1
Uzbekjon Avatar answered Oct 18 '22 17:10

Uzbekjon


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

like image 1
Pedro Lobito Avatar answered Oct 18 '22 17:10

Pedro Lobito