【问题标题】:How to detect that a regex that matches and capture has not found a match如何检测匹配和捕获的正则表达式未找到匹配项
【发布时间】:2021-09-24 20:51:29
【问题描述】:

我有以下 javascript 代码,它使用正则表达式来匹配某个字符串是否包含国际格式的电话号码并捕获该号码

var myString1 = "some other string +123456789 some other string";
var myString2 = "some other string 123456789 some other string";

var regex = new RegExp("\\+(\\d+)");
var number = myString1.match(regex)[1];

if (typeof (number) == "string") {
  // some positive actions
}
else {
  // some negative actions
}

如果存在匹配,代码将完美运行,对于上面的代码,if 语句将返回 true,因此 一些积极的行动将被执行

问题是如果没有找到匹配项(例如当使用myString2 时),if 语句既不会返回 true 也不会返回 false 意味着 一些负面的操作也赢了'不被执行

我试过了

if (number == "" || number == null) {
  // some negative actions
}
else {
  // some positive actions
}

如果有匹配,else 部分将起作用,但如果没有匹配,则不会检测是否没有匹配。我尝试在使用mystring2 时使用typeof(number) 打印number 的数据类型,但它也没有返回任何内容。它不为 null 或为空

我可以使用什么条件来检测是否不匹配

注意:我必须使用正则表达式

【问题讨论】:

    标签: javascript html regex


    【解决方案1】:

    这不起作用,因为您在调用 match() 后立即获得了数组中的第二项。如果没有匹配,它会返回null,因此你会得到一个错误。

    相反,首先检查match() 方法是否返回一个数组(使用Array.isArray() 或简单地检查null),然后获取第二项:

    var myString1 = "some other string +123456789 some other string";
    var myString2 = "some other string 123456789 some other string";
    
    var regex = new RegExp("\\+(\\d+)");
    var number = myString2.match(regex);
    
    if (Array.isArray(number)) {
      number = number[1];
      console.log('positive');
    } else {
      console.log('negative');
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 2010-12-03
      相关资源
      最近更新 更多