简体   繁体   English

JavaScript - 匹配 0.01 到 99 之间的任何数字的正则表达式

[英]JavaScript - RegEx that matches any number between 0.01 and 99

I'm working on a form where there's an "Interest Rate" Field which has accept values between 0.01 and 99.00我正在处理一个表单,其中有一个“利率”字段,其接受值介于 0.01 和 99.00 之间

I've already looked a RegEx Up from 0.01 to 99.99 in a regular expression .我已经在正则表达式中查看了从 0.01 到 99.99的 RegEx Up。 This almost does the trick.这几乎可以解决问题。 The only challenge that I'm getting is to make it to NOT MATCH numbers from 99.01 to 99.99.我得到的唯一挑战是使它不匹配从 99.01 到 99.99 的数字。

I've updated it to cater to up to 10 digits after the decimal point.我已经对其进行了更新,以适应小数点后最多 10 位数字。

Test Data:测试数据:

Should only match numbers between 0.01 and 99.00应该只匹配 0.01 到 99.00 之间的数字

Should Not Match不应该匹配

  • 00.00 00.00
  • 100.134234 100.134234
  • 99.01234 // this is matching, but should not match with my current RegEx. 99.01234 // 这是匹配的,但不应该与我当前的 RegEx 匹配。
  • 100 100

Should Match应该匹配

  • 0.01 0.01
  • 0.10 0.10
  • 1.233 1.233
  • 3.20 3.20
  • 4.655 4.655
  • 5.112 5.112
  • 99.00 99.00
  • 99.0 99.0

I've already created a RegEx101 Sandbox which I feel might be useful.我已经创建了一个我觉得可能有用的RegEx101 沙盒

At the beginning, add a negative lookahead for 99 followed by anything but .00 :在开始时,为 99 添加负前瞻,后跟除.00之外的任何内容:

(?!99\.0*[^0\n])

https://regex101.com/r/R63oyb/10 https://regex101.com/r/R63oyb/10

excluding 99.01 and 99.10 and so on, but permitting 99.00 and 99 .不包括99.0199.10等,但允许99.0099

Here's my approach:这是我的方法:

^(?:(?![0.]+$|99)|(?=(?:99|99\.0+)$))\d{1,2}(?:\.\d+)?$

See the test cases查看测试用例

  • \d{1,2}(?:\.\d+)? Matches 1-2 digit numbers optionally followed by a decimal point and some digits匹配 1-2 位数字,可选地后跟小数点和一些数字
  • (?:(?.[0?]+$|99)|(?=(:.99|99\.0+)$))
    • (?.[0.]+$|99) Tests if the number is only formed by 0 and . (?.[0.]+$|99)测试数字是否仅由0. or starting with 99 , fails it.或以99开头,失败。 This eliminates 0 and 99这消除了099
    • |(?=(?:99|99\.0+)$) Unless the number is pure 99 or 99 followed by a decimal point and a bunch of 0 s, let it pass. |(?=(?:99|99\.0+)$)除非数字是纯9999后跟一个小数点和一堆0 ,否则让它通过。

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

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