jQuery 带有逗号分隔符的数字的正则表达式验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3455988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:29:37  来源:igfitidea点击:

Regex validation for numbers with comma separator

jqueryregexvalidation

提问by Suvonkar

Need a regular expression to validate number with comma separator. 1,5,10,55is valid but 1,,,,10is not valid.

需要一个正则表达式来验证带有逗号分隔符的数字。 1,5,10,55有效但1,,,,10无效。

回答by Kobi

This should do it:

这应该这样做:

^\d+(,\d+)*$

The regex is rather simple: \d+is the first number, followed by optional commas and more numbers.

正则表达式相当简单:\d+是第一个数字,后跟可选的逗号和更多数字。

You may want to throw in \s*where you see fit, or remove all spaces before validation.

您可能想要\s*在您认为合适的地方加入,或者在验证之前删除所有空格。

  • To allow negative numbers replace \d+with [+-]?\d+
  • To allow fractions: replace \d+with [+-]?\d+(?:\.\d+)?
  • 允许负数替换\d+[+-]?\d+
  • 允许分数:替换\d+[+-]?\d+(?:\.\d+)?

回答by polygenelubricants

Here are the components of the regex we're going to use:

以下是我们将要使用的正则表达式的组件:

  • \dis the shorthand for the digit character class
  • +is one-or-more repetition specifier
  • *is zero-or-more repetition specifier
  • (...)performs grouping
  • ^and $are the beginning and end of the line anchors respectively
  • \d是数字字符类的简写
  • +是一个或多个重复说明符
  • *是零个或多个重复说明符
  • (...)进行分组
  • ^$分别是线锚的开始和结束

We can now compose the regex we need:

我们现在可以编写我们需要的正则表达式:

^\d+(,\d+)*$

That is:

那是:

from beginning...
|    ...to the end
|          |
^\d+(,\d+)*$              i.e. ^num(,num)*$
 \_/  \_/ 
 num  num

Note that the *means that having just one number is allowed. If you insist on at least two numbers, then use +instead. You can also replace \d+with another pattern for the number to allow e.g. sign and/or fractional part.

请注意,这*意味着允许只有一个数字。如果您坚持至少使用两个数字,请+改用。您还可以替换\d+为其他模式的数字以允许例如符号和/或小数部分。

References

参考



Advanced topics: optimization

进阶课题:优化

Optionally you can make the brackets non-capturingfor performance:

您可以选择使括号不捕获性能:

^\d+(?:,\d+)*$

And if the flavor supports it, you can make all repetition possessivein this case:

如果口味支持它,在这种情况下,您可以使所有重复都具有所有格

^\d++(?:,\d++)*+$

References

参考

回答by Sachin R

^[0-9]*(,){1}[0-9]*/

try this

尝试这个