【问题标题】:RegExp not matching results正则表达式不匹配结果
【发布时间】:2016-11-10 16:01:48
【问题描述】:

我正在尝试匹配 javascript 中的模式。

以下是示例:

var pattern = "/^[a-z0-9]+$/i"; // This is should accept on alpha numeric characters.
var reg = new RegExp(pattern);
console.log("Should return false : "+reg.test("This $hould return false"));
console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

当我运行它时,我得到的两个结果都是错误的。 我确实认为我缺少一些简单的东西。但是有点迷茫。

提前致谢。

【问题讨论】:

    标签: javascript regex alphanumeric


    【解决方案1】:

    如果您使用 RegExp 构造函数,则不需要使用斜杠。 您可以使用不带双引号的封闭斜杠来表示正则表达式,或者将字符串(通常用引号括起来)传递给 RegExp构造函数:

    var pattern = "^[a-z0-9]+$"; // This is should accept on alpha numeric characters.
    var reg = new RegExp(pattern, "i");
    console.log("Should return false : "+reg.test("This $hould return false"));
    console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

    【讨论】:

      【解决方案2】:

      你的模式是错误的。您不需要在这里使用 RegExp 构造函数。您需要忽略大小写标志或将大写字母添加到范围。

      var reg = /^[a-zA-Z0-9]+$/;
      console.log("Should return false : "+reg.test("This $hould return false"));
      console.log("Should return true : "+reg.test("Thisshouldreturntrue"));

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-06
        • 1970-01-01
        • 2016-11-07
        • 2022-12-09
        • 2022-12-11
        • 2017-12-04
        • 1970-01-01
        • 2021-10-22
        相关资源
        最近更新 更多