正则表达式javascript,为什么点和逗号匹配\ [英] Regex javascript, why dot and comma are matching for \

查看:469
本文介绍了正则表达式javascript,为什么点和逗号匹配\的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个正则表达式'^ [0-9] + \。?[0-9] * $'匹配12.2和12,2?

Why this regex '^[0-9]+\.?[0-9]*$' match for 12.2 and 12,2 ?

jsFiddle

var dot = '12.2',
    comma = '12,2',
    regex = '^[0-9]+\.?[0-9]*$';

alert( dot.match(regex) );
alert( comma.match(regex) );

虽然它适用于 regexpal.com

推荐答案

因为变量 regex 是一个字符串,转义序列 \。只是,它匹配任何字符(换行符除外)。如果您更改正则表达式的定义以使用RegExp文字语法或转义转义字符( \\。),那么它将按预期工作。

Because the variable regex is 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.

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));

这篇关于正则表达式javascript,为什么点和逗号匹配\的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆