我正在尝试创建一个与以下内容匹配的正则表达式:
这是我到目前为止的正则表达式,它并不适用于所有情况:
/\d{1,}\.{0,1}\d{1,2}/
所有这些测试用例都应该通过
1.9
1
12
1211.1
121234.14
所有这些测试用例都不应该通过
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
答案 0 :(得分:2)
<强> EDITED 强>
我认为它会解决..
/^\d{1,}(\.\d{1,2}){0,1}$/
我的测试用例:
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
答案 1 :(得分:1)
r = /
\A # match beginning of string
\d+ # match >=1 digits
(?!\d) # do not match a digit (negative lookahead)
(?:\.\d{1,2})? # optionally match a period and 1 or 2 digits in a non-capture group
\z # match end of string
/x # free-spacing regex definition mode
"312.64" =~ r #=> 0
"312.643" =~ r #=> nil
"3.64" =~ r #=> 0
"a3.64" =~ r #=> nil
"a.64" =~ r #=> nil
"23.a64" =~ r #=> nil
"31" =~ r #=> 0
这个正则表达式通常是
r = /\A\d+(?!\d)(?:\.\d{1,2})?\z/