javascript 如何在javascript中使用正则表达式检查字符串是否仅包含数字、逗号和句点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21907466/
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
How can I check if a string contains only numbers, comma and periods with regex in javascript?
提问by Weblurk
I have an input field that I will only accept numbers, commas and periods. How can I test if the string is valid according to these rules?
我有一个输入字段,我只接受数字、逗号和句点。如何根据这些规则测试字符串是否有效?
I have tried the following:
我尝试了以下方法:
var isValid = /([0-9][,][.])$/.test(str);
but it's not working. isValid variable is always false.
但它不起作用。isValid 变量总是假的。
回答by Tibos
Your regexp expects one character from the first class (0-9), then one from the second class (comma) then one from the last class (dot). Instead you want any number of characters (*) from the class containing digits, commas and dots ([0-9,.]
). Also, you don't need the parenthesis:
您的正则表达式需要来自第一类(0-9)的一个字符,然后来自第二类(逗号)的一个字符,然后来自最后一类(点)的一个字符。相反,您需要包含数字、逗号和点 ( [0-9,.]
)的类中的任意数量的字符 (* )。此外,您不需要括号:
var isValid = /^[0-9,.]*$/.test(str);
DEMO (and explanation): http://regex101.com/r/yK6oF4
演示(和解释):http: //regex101.com/r/yK6oF4
回答by Justin Patel
var regex = "[-+]?[0-9].?[0-9]"
var regex = "[-+]?[0-9] .?[0-9]"
This works perfect for decimal number & Integer. e.g. 1 - true
这适用于十进制数和整数。例如 1 - 真
1.1 - true
1.1 - 真
1.1.1 - false
1.1.1 - 假
1.a - false
1.a - 假