正则表达式 javascript,为什么点和逗号匹配 \
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5469641/
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
Regex javascript, why dot and comma are matching for \
提问by canardman
Why this regex '^[0-9]+\.?[0-9]*$'match for 12.2 and 12,2 ?
为什么这个正则表达式'^[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) );
While it works on regexpal.com
虽然它适用于regexpal.com
回答by maerics
Because the variable regexis a string the escape sequence \.is just ., which matches any character (except newline). If you change the definition of regex to use RegExp literal syntax or escape the escape character (\\.) then it will work as you expect.
因为变量regex是一个字符串,所以转义序列\.只是.,它匹配任何字符(换行符除外)。如果您将 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));
回答by Stephen Chung
Are you sure you don't need to escape the back-slash? It is in a string, you know...
您确定不需要转义反斜杠吗?它在一个字符串中,你知道...
regex = /^[0-9]+\.?[0-9]*$/
or
或者
regex = "^[0-9]+\.?[0-9]*$"
Actually, I'd recommend that you write it this way:
实际上,我建议你这样写:
regex = /^\d+(\.\d+)?$/
回答by Effata
Since you write your regex in a string, you need to escape the slash.
由于您将正则表达式写入字符串,因此需要对斜杠进行转义。
regex = '^[0-9]+\\.?[0-9]*$';
regex = '^[0-9]+\\.?[0-9]*$';
回答by Cristian Necula
Your regex should be
你的正则表达式应该是
regex = /^[0-9]+\.?[0-9]*$/;
Consult https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexpfor proper syntax.
有关正确的语法,请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp。

