Matching regular expression with a numeric value and decimal

I need to match a regex for a value that is a decimal point numeric. I currently have /^-?[0-9.06.2012\d*(.\d+)/ but it does not account for .00 How can I fix this

Present value:

1
1.0 
1.33
.00

Current Invalid:

Alpha Character 
+4
source share
7 answers

You need to handle 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 everything optional and provide at least one digit there:

/\A-?+(?=.??\d)\d*\.?\d*\z/
#  ^  ^  ^        ^---- optional dot
#  |  |  '---- optional char (non-greedy)
#  |  '---- lookahead assertion: means "this position is followed by"
#  '---- optional "-" (possessive)

. - ?? , , , . ?. ( , "unknow char", , .)

+5

, `(?:...)?:

/\A(?:-?[0-9]\d*)?(.\d+)/

?: , , , .

+1

: /\d*\.?\d*/?

0

, , 3:

N
N.NN
.NN

i.e.:

(\d+\.\d+|\d+|\.\d+)

regex 101 Demo

0

- ^\-?[0-9\.]+ (^\-?[0-9\.]+), . 0 9 (.) (-).

- Rubular .

0

.

def match_it(str)
  str if str.gsub(/[\d\.-]/, '').empty? && Float(str) rescue nil
end

match_it "1"     #=> "1" 
match_it "1.0"   #=> "1.0" 
match_it "-1.0"  #=> "-1.0" 
match_it "1.33"  #=> "1.33" 
match_it ".00"   #=> ".00" 
match_it "-.00"  #=> "-.00" 
match_it "1.1e3" #=> nil 
match_it "Hi!"   #=> nil 
0

.:

(^-?[\d+]*[\.\d+]*)

:)

0

All Articles