[英]Regex in javascript to allow only numbers, commas, and a single decimal point
Currently i am using this regex to match for positive numbers with a single decimal point 目前,我正在使用此正则表达式来匹配带单个小数点的正数
/^\d+(\.\d+)?$/
But this doesn't allow commas. 但这不允许逗号。 How can i modify this to allow zero or more commas before the decimal point?
我如何修改它以允许小数点前有零个或多个逗号?
Example : 范例:
EDIT: 编辑:
Valid values 有效值
The values can be entered with or without comma. 值可以带或不带逗号输入。 The datatype of this field is SQL MONEY, so it will handle comma's.
该字段的数据类型为SQL MONEY,因此它将处理逗号。
need 需要
/^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/
See the regex demo 见正则表达式演示
Details 细节
^
- start of string ^
-字符串的开头 (?:\\d{1,3}(?:,\\d{3})*|\\d+)
- Either of: (?:\\d{1,3}(?:,\\d{3})*|\\d+)
-以下任一项:
\\d{1,3}(?:,\\d{3})*
- 1 to 3 digits followed with 0+ sequences of a ,
and 3 digits \\d{1,3}(?:,\\d{3})*
- 1到3位数字用的0+序列,
和3位数字 |
- or \\d+
- 1 or more digits \\d+
-1个或更多数字 (?:\\.\\d+)?
- an optional sequence of .
.
and 1+ digits $
- end of string. $
-字符串结尾。 var strs = [',,,,', '111', '11,111', '11,111.0', '111111']; var re = /^(?:\\d{1,3}(?:,\\d{3})*|\\d+)(?:\\.\\d+)?$/; for (var s of strs) { console.log(s + " => " + re.test(s)); }
This is a very simple general solution, without any assumptions about how many digits are needed. 这是一个非常简单的通用解决方案,无需对需要多少位数进行任何假设。
/^\d[\d,]*(\.\d+)?$/
[\\d,]
will match digits or commas. [\\d,]
将匹配数字或逗号。
You could make the regex more complicated if you really need it to be more specific. 如果确实需要正则表达式更具体,则可以使其更复杂。
I would use this 我会用这个
^(?:\d{1,3}(,\d{3})*|\d+|\d{2}(?:,\d{2})*,\d{3})(?:\.\d+)?$
See demo and explanation 参见演示和说明
This is pretty hard to read but I'll explain it 这很难读,但我会解释
/^(?:\\d+)(?:(?:\\d+)|(?:(?:,\\d+)?))+(?:\\.\\d+)?$/
All the ?:
are just to explicitly say to the regex engine "Don't capture the following group matched by this paren). 所有
?:
只是要对正则表达式引擎明确地说“不要捕获此括号所匹配的以下组)。
The simplified version would be 简化的版本是
/^(\\d+)((\\d+)|((,\\d+)?))+(\\.\\d+)?$/
But it'd capture a lot of matching groups for no reason so I removed them 但是它无缘无故地捕获了很多匹配组,所以我删除了它们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.