Neil Neil - 3 months ago 11
Ruby Question

Ruby Regular Expression: 1-2 digits required after period if period is present

I am trying to create a regular expression that matches the following:


  • one or more digits

  • allow zero to 1 period after the first digits

  • if a period is present


    • require 1 - 2 digits after the period




Here is the regex I have so far, it doesn't work for all cases:

/\d{1,}\.{0,1}\d{1,2}/


All of these test cases should pass

1.9
1
12
1211.1
121234.14


All of these test cases should not pass

z
z1
z.5
z.55 # no letters
.9 # required one or more digits before the period if period is present
34. # required 1-2 digits after period if period is present
4..3
4..55 # only 1 period
4.333 # only 1-2 digits after period
111,222.44 # no comma

Answer

EDITED

I think it will resolve..

/^\d{1,}(\.\d{1,2}){0,1}$/

My test case:

2.3.0 :129 > regex = /^\d{1,}(\.\d{1,2}){0,1}$/
 => /^\d{1,}(\.\d{1,2}){0,1}$/
2.3.0 :161 > regex.match("1.9")
 => #<MatchData "1.9" 1:".9"> 
2.3.0 :162 > regex.match("1")
 => #<MatchData "1" 1:nil> 
2.3.0 :163 > regex.match("12")
 => #<MatchData "12" 1:nil> 
2.3.0 :164 > regex.match("1211.1")
 => #<MatchData "1211.1" 1:".1"> 
2.3.0 :165 > regex.match("121234.14")
 => #<MatchData "121234.14" 1:".14"> 
2.3.0 :166 > regex.match("z")
 => nil 
2.3.0 :167 > regex.match("z1")
 => nil 
2.3.0 :168 > regex.match("z.5")
 => nil 
2.3.0 :169 > regex.match("z.55")
 => nil 
2.3.0 :170 > regex.match(" .9")
 => nil 
2.3.0 :171 > regex.match("34.")
 => nil 
2.3.0 :172 > regex.match("4..3")
 => nil 
2.3.0 :173 > regex.match("4..55")
 => nil 
2.3.0 :174 > regex.match("4.333")
 => nil 
2.3.0 :175 > regex.match("111,222.44")
 => nil