admin管理员组文章数量:1401922
Using JavaScript, I need to accept only numbers and mas.
The regex pattern I am using is as follows
var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
How do I accept mas in the above pattern So that values like 3200
or 3,200
or 3,200.00
and so are valid?
There are similar questions that only partially deal with this:
- Regex validation for numbers with ma separator (only whole numbers with no fractional part)
- Decimal number regular expression, where digit after decimal is optional (no ma separation, fractional part limited to 1 digit)
- Javascript function need allow numbers, dot and ma (the dots, mas and digits are matched in any order)
Using JavaScript, I need to accept only numbers and mas.
The regex pattern I am using is as follows
var pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
How do I accept mas in the above pattern So that values like 3200
or 3,200
or 3,200.00
and so are valid?
There are similar questions that only partially deal with this:
- Regex validation for numbers with ma separator (only whole numbers with no fractional part)
- Decimal number regular expression, where digit after decimal is optional (no ma separation, fractional part limited to 1 digit)
- Javascript function need allow numbers, dot and ma (the dots, mas and digits are matched in any order)
- 1 Why not test if the string is a valid number instead of trying to match it with a regex? – James Montagne Commented Oct 27, 2015 at 13:01
1 Answer
Reset to default 4Use 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]+
- 1 or more digits,
- a ma
0 or more times (thanks to *
quantifier).
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
^[-+]?[0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?$
See another demo
Here, (?:,[0-9]{3})*
matches 0 or more sequences of a ma and 3-digit substrings ([0-9]{3}
). {3}
is a limiting quantifier matching exactly 3 occurrences of the preceding subpattern.
本文标签: javascriptRegex to validate commaseparated numbers with optional fractional partsStack Overflow
版权声明:本文标题:javascript - Regex to validate comma-separated numbers with optional fractional parts - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744328694a2600854.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论