[英]Regex to validate comma-separated numbers with optional fractional parts
Using JavaScript, I need to accept only numbers and commas.使用 JavaScript,我只需要接受数字和逗号。
The regex pattern I am using is as follows我使用的正则表达式模式如下
var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
How do I accept commas in the above pattern So that values like 3200
or 3,200
or 3,200.00
and so are valid?我如何接受上述模式中的逗号,以便
3200
或3,200
或3,200.00
等值有效?
There are similar questions that only partially deal with this:有类似的问题只部分解决了这个问题:
Use the following regex:使用以下正则表达式:
^[-+]?(?:[0-9]+,)*[0-9]+(?:\.[0-9]+)?$
See regex demo见正则表达式演示
The basic change here is the addition of (?:[0-9]+,)*
subpattern that matches:这里的基本变化是添加了
(?:[0-9]+,)*
匹配的子模式:
[0-9]+
- 1 or more digits [0-9]+
- 1 位或更多位,
- a comma ,
- 逗号0 or more times (thanks to *
quantifier). 0 次或多次(感谢
*
量词)。
I also used non-capturing groups so that regex output is "cleaner".我还使用了非捕获组,以便正则表达式输出“更干净”。
If you need to check for 3-digit groups in the number, use如果您需要检查号码中的 3 位组,请使用
^[-+]?[0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?$
See another demo看另一个演示
Here, (?:,[0-9]{3})*
matches 0 or more sequences of a comma and 3-digit substrings ( [0-9]{3}
).这里,
(?:,[0-9]{3})*
匹配 0 个或多个逗号序列和 3 位子字符串 ( [0-9]{3}
)。 {3}
is a limiting quantifier matching exactly 3 occurrences of the preceding subpattern. {3}
是一个限制量词,正好匹配前面子模式的 3 次出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.