正则表达式限制数字在0.01和1之间 – JAVA

huangapple go评论63阅读模式
英文:

Regex for limiting numbers between 0.01 and 1 - JAVA

问题

我想找一个正则表达式,允许在两位小数的情况下介于 0.01 到 1 之间的值(包括 0.01 和 1)。不允许出现 0.00、0.0 或 0。不允许大于 1 的值(例如,1.01、1.1 等)。能帮忙吗?

英文:

I want to find a regex which allows values between 0.01 and 1 , both inclusive upto two decimal places max. 0.00 , 0.0 or 0 is not allowed . Values greater than 1 (eg , 1.01 , 1.1 etc. is not allowed). Can i get help?

答案1

得分: 1

寻找其中一个好的模式:
- `(^0\.[0-9][1-9]$)`: 0.xy(其中 x 是数字 1-9,y 是数字 0-9)
- `(^0\.[1-9]0*$)`: 0.x(其中 x 是数字 1-9,可选的零)
- `(^1\.0{1,2}$)|(^1$)`: 允许的 1 的表示之一(1, 1.0, 1.00)

`(^0\.[0-9][1-9]$)|(^0\.[1-9]0*$)|(^1\.0{1,2}$)|(^1$)`

使用 `^` 和 `$` 应该处理边缘测试案例:

    0
    0.0
    0.00
    0.01 - 匹配
    0.1  - 匹配
    0.01 - 匹配
    0.10 - 匹配 
    0.11 - 匹配 
    0.1.1
    0.11.1
    00
    00.1.1
    1    - 匹配 
    1.0  - 匹配
    1.00 - 匹配 
    1.10
    1.11
    0.001
    0.111

详见 https://regex101.com/r/U4I9sK/2
英文:

Searching for one of good patterns:

  • (^0\.[0-9][1-9]$): 0.xy (where x is digit 1-9 and y is digit 0-9)
  • (^0\.[1-9]0*$): 0.x (where x is digit 1-9, with optional zero)
  • (^1\.0{1,2}$)|(^1$): one of allowed notations for 1 (1, 1.0, 1.00)

(^0\.[0-9][1-9]$)|(^0\.[1-9]0*$)|(^1\.0{1,2}$)|(^1$)

With ^ and $ should handle edge testcases:

0
0.0
0.00
0.01 - match
0.1  - match
0.01 - match
0.10 - match 
0.11 - match 
0.1.1
0.11.1
00
00.1.1
1    - match 
1.0  - match
1.00 - match 
1.10
1.11
0.001
0.111

See https://regex101.com/r/U4I9sK/2

答案2

得分: 0

并不是一个正则表达式,而是一个返回你期望值的方法。你需要完成两件事:范围比较和长度比较(如果范围合适)。

就像这样,

public static boolean isGood(double x){
        return x >= 0.01 
            && x <= 1.0 
            && String.valueOf(x).split("\\.")[1].length() <= 2;
}
英文:

Not a regex, but a method to return what you expected. You need to do two things: range comparison & length comparison if range is satisified.

Like so,

public static boolean isGood(double x){
        return x&gt;=0.01 
            &amp;&amp; x&lt;=1.0 
            &amp;&amp; String.valueOf(x).split(&quot;\\.&quot;)[1].length()&lt;=2;
}

答案3

得分: 0

当你说 'allow' 时,你是指要排除,即完全排除,还是想要转换成长十进制?

如果是排除的话,正则表达式为:

^(1(\.0?0?)?|0?\.(0[1-9]|[1-9]\d?))$

这还允许仅为 '1.'。

如果是要转换的话,你可以使用一系列的条件判断和设置精度,就像这里回答的那样:
https://stackoverflow.com/questions/10631813/javascript-tofixed-equivalent-in-java

英文:

When you say 'allow' do you mean to disallow, ie excluded completely, or are you wanting to convert the long decimal?

If excluding then regex =

 ^(1(\.0?0?)?|0?\.(0[1-9]|[1-9]\d?))$

This also allows for just '1.'.

if converting, then you can use a combination of if conditions and setScale 'as answered here:
https://stackoverflow.com/questions/10631813/javascript-tofixed-equivalent-in-java&#39;

huangapple
  • 本文由 发表于 2020年10月14日 13:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64347204.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定