使用正则表达式验证掩码和货币限制范围

时间:2019-09-23 10:53:25

标签: regex

我正在开发应用程序上的功能,现在有一个需求,需要正则表达式来验证用户键入的掩码(可以)并限制键入的范围。例如,如果我输入:

100,00 - can pass
50,00 - can pass
100.000,00 - can pass
100.000,01 - more than 100k not pass

现在,我正在使用我的正则表达式来验证掩码,但我不能限制范围...

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

任何人都知道如何实现此限制吗?

1 个答案:

答案 0 :(得分:0)

您需要分别验证100.000,00部分。另外,请记住\.与一个点匹配,并且在您当前的正则表达式中,您可以无限次重复,因此100.000.000.000,00当前通过。

尝试一下:

^\$?(?:100\.000,00|(?:[1-9]\d?\.\d{3}|[1-9]\d{0,2}|0)\,\d{1,2})$

测试live on regex101.com

说明:

^                   # Start of string
\$?                 # Match optional dollar sign
(?:                 # Group: Match either
 100\.000,00        # 100.000,00
|                   # or
 (?:                # Group: Match either
  [1-9]\d?\.\d{3}   # a number between 1.000 and 99.999
 |                  # or
  [1-9]\d{0,2}      # a number between 1 and 999  
 |                  # or
  0                 # 0
 )                  # End of inner group
 \,\d{1,2}          # Match , and one or two digits
)                   # end of outer group
$