简体   繁体   English

带 2 位小数的百分比的正则表达式

[英]Regex for percentage with 2 decimal places

I am looking to build 2 regex with those constraints:我希望构建具有这些约束的 2 个正则表达式:

  • 0 to 100 0 到 100
  • 2 decimals places (like 15.25 or 0.01) 2 位小数(如 15.25 或 0.01)
  • But 100.01 is not acceptable但是 100.01 是不可接受的
  • No negative number没有负数

For the second regex, I need it to go up to 200 instead of 100 but same for the rest.对于第二个正则表达式,我需要它达到 200 而不是 100,但其余部分相同。

Currently, I have this one for 0 to 100:目前,我有这个 0 到 100:

^([0-9]|[1-9][0-9]|100)?$

and this one for 200这个要200

^([01]?[0-9][0-9]?|200)?$

I can get 0 to 100 or 200 numbers but without decimal places.我可以获得 0 到 100 或 200 个数字,但没有小数位。

First regex : ^([0-9]{1,2}|[0-9]{1,2}\.[0-9]{2}|100)?$第一个正则表达式^([0-9]{1,2}|[0-9]{1,2}\.[0-9]{2}|100)?$

regex101.com正则表达式101.com

Second regex : ^(([01]?[0-9][0-9]?)|([01]?[0-9][0-9]?\.[0-9]{2})|200)?$第二个正则表达式^(([01]?[0-9][0-9]?)|([01]?[0-9][0-9]?\.[0-9]{2})|200)?$

It also covers values such as 11.44 , 199.11它还涵盖诸如11.44199.11之类的值

regex101.com正则表达式101.com

You can extend your regex like this:您可以像这样扩展您的正则表达式:

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

You can try it here: https://regex101.com/r/HBidWk/1您可以在这里尝试: https ://regex101.com/r/HBidWk/1

This is for 0-100这是0-100

Here are the regex patterns I came up with from having understood the OP's requirements as follows...这是我在理解 OP 的要求后提出的正则表达式模式,如下所示......

  1. As for the 1st one至于第一个

    • "... from 0.00 (but not 00.00 ) to 99.99 to 100 (but not 100.00 )" “...从0.00 (但不是00.00 )到99.99100 (但不是100.00 )”

    • the pattern would be...模式将是...

       /^(?:[1-9]?\d\.\d{2}|100)$/
    • ... and the explanation could be found at this pattern's test side: ...并且可以在该模式的测试端找到解释:

      /^(?:[1-9]?\d\.\d{2}|100)$/ . /^(?:[1-9]?\d\.\d{2}|100)$/ .

  2. As for the 2nd one至于第二个

    • "... from 0.00 (but not 00.00 ) to 199.99 to 200 (but not 200.00 )" “......从0.00 (但不是00.00 )到199.99200 (但不是200.00 )”

    • the pattern would be...模式将是...

       /^(?:(?:1\d{2}|[1-9]?\d)\.\d{2}|200)$/
    • ... and the explanation could be found at this pattern's test side: ...并且可以在该模式的测试端找到解释:

      /^(?:(?:1\d{2}|[1-9]?\d)\.\d{2}|200)$/ . /^(?:(?:1\d{2}|[1-9]?\d)\.\d{2}|200)$/ .

  3. Due to a first misread from my side I also implemented a much more complex由于我这边的第一次误读,我还实现了一个更复杂的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM