简体   繁体   English

RegEx - 如何将百分比验证嵌入到我的货币验证中

[英]RegEx - How can I embed PERCENTAGE Validation into my CURRENCY Validation

I need to validate a field that can be inputed as CURRENCY, or NUMERIC, or PERCENTAGE.我需要验证可以输入为 CURRENCY、NUMERIC 或 PERCENTAGE 的字段。 I haven't seen any posts for ALL 3 conditions at once so wanted to ask the community.我还没有同时看到所有 3 个条件的任何帖子,所以想问问社区。

I found the following code on here (thanks Gary!!) that works great for validating currency or numerics at the same time.我在这里找到了以下代码(感谢 Gary !!),它非常适合同时验证货币或数字。
(?=.)^\\$?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\\.[0-9]{1,2})?$

Regex currency validation 正则表达式货币验证

How do you update this expresssion to validate for percentages as well?您如何更新此表达式以验证百分比? Basically I would like to allow a percent symbol at the very end IF基本上我想在最后允许一个百分比符号 IF
- they don't enter a dollar sign - 他们不输入美元符号
- (if possible I'd like to also validate that if they enter a percent symbol then the value can't be over 100, but I can live w/o this validation) -(如果可能的话,我还想验证一下,如果他们输入百分比符号,则该值不能超过 100,但我可以在没有此验证的情况下生存)

I might think of a cleaner way to do it later, but for now this should work以后我可能会想到一个更简洁的方法,但现在这应该可行

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

It simply takes the regex you borrowed from me and adds它只需要你从我那里借来的正则表达式并添加

  • An optional '%' at the end (in addition to the already optional '$' at the beginning): %?一个可选的 '%' 结尾(除了开头已经可选的 '$'): %? . .
  • A negative lookahead to check that it doesn't have both: (?!\\$.+?%)检查它是否没有两者的否定前瞻: (?!\\$.+?%)
  • A positive lookahead to ensure that it has one or the other (since they were both optional): (?=\\$.+|.+%) make sure there's a number somewhere (since everything is individually optional): (?=.*\\d)一个积极的前瞻以 确保它有一个或另一个(因为它们都是可选的): (?=\\$.+|.+%) 确保某处有一个数字(因为一切都是单独的可选): (?=.*\\d)

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

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