为什么这个正则表达式'^[0-9]+\.?[0-9]*$'
匹配12.2和12,2?
var dot = '12.2',
comma = '12,2',
regex = '^[0-9]+\.?[0-9]*$';
alert( dot.match(regex) );
alert( comma.match(regex) );
虽然它适用于regexpal.com
答案 0 :(得分:41)
因为变量regex
是一个字符串,转义序列\.
只是.
,它匹配任何字符(换行符除外)。如果您更改正则表达式的定义以使用RegExp文字语法或转义转义字符(\\.
),那么它将按预期工作。
var dot = '12.2'
, comma = '12,2'
, regex = /^[0-9]+\.?[0-9]*$/;
// or '^[0-9]+\\.?[0-9]*$'
alert(dot.match(regex));
alert(comma.match(regex));
答案 1 :(得分:9)
你确定你不需要逃避反斜杠吗?它是一个字符串,你知道......
regex = /^[0-9]+\.?[0-9]*$/
或
regex = "^[0-9]+\\.?[0-9]*$"
实际上,我建议你这样写:
regex = /^\d+(\.\d+)?$/
答案 2 :(得分:2)
由于您在字符串中编写正则表达式,因此需要转义斜杠。
regex = '^[0-9]+\\.?[0-9]*$';
答案 3 :(得分:1)
你的正则表达式应该是
regex = /^[0-9]+\.?[0-9]*$/;
请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp以获得正确的语法。