【问题标题】:Calculating the length of an array of regular expressions计算正则表达式数组的长度
【发布时间】:2017-02-28 22:32:03
【问题描述】:

我在这里有一个函数,用于根据给定的正则表达式数组检查元素。我传递的数组包含十个不同的正则表达式。

var regExAlphabet = /[a-z]/;
var regExNumbers = /[0-9]/;
var regExWhile = /while/;
var regExIf = /if/;
var regExElse = /else/;
var regExTrue = /true/;
var regExFalse = /false/;
var regExInt = /int/;
var regExString = /string/;
var regExBoolean = /boolean/;

var regexList = [regExAlphabet, regExNumbers, regExTrue, regExFalse,
regExInt, regExString, regExBoolean, regExWhile, regExIf, regExElse];

function loopThroughOptions(regexList, element) {
  for (var i = 0; i < regexList.length; i++)
    failSafe(regexList[i], element) // failSafe is defined but not shown
}

var aString = "a";

loopThroughOptions(regexList, aString);

当我运行这个时,我得到一个未捕获的 typeError: cannot read property length of undefined in my loopThroughOptions 函数。为什么会这样?我该如何解决?

编辑:看来我需要发布 failSafe 功能。它很长。试一试吧。

var tokenList = []; // list of discovered tokens
var substringsArray = []; // any strings that are not tokens go here

    function substringsHandler(array) {
  for (var i = 0; i < substringsArray.length; i++) {
    for (var y = 0; y < regexList.length; y++) {
      failSafe(regexList[y], substringsArray[i])
    }
  }
}    

function findAMatch(value) {
    if (value == "a")
        console.log("matched a");
}

function findACharMatch(value) {
    if (value == "a")
        console.log("matched a");
}

function failSafe(regEx, element) {

  if (regEx.test(element) && element.length > 1) { // if the token is there
    var x = regEx.exec(element); // give us more information on the element
    var value = x["0"]; // keep track of the value of the token
    var index = x.index; // keep track of the index
    var substring = value;
    console.log(index);
    console.log(substring.length);
    console.log(element.length);
    tokenList.push({
      value: substring,
      indexFound: index});
    console.log(tokenList[0]);
    if (index > 0 && index + substring.length - 1 < element.length) { // if we found a token in the middle of a string
      console.log("Found token in the middle of the string.");
       substringsArray.push({ // give us the half that comes before the match
          value: element.substring(0, index),
          indexFound: 0
          });

       substringsArray.push({ // give us the rest of the string that occurs after the match
         value: element.substring(index + value.length),
         indexFound: index + value.length
         });

        substringsHandler(substringsArray);
         // all successful token finds get sent to tokenList to search for a match
         // if nothing is found, then everything gets translated to characters or digits
   }       else if (index > 0 && index + substring.length - 1 == element.length)   { // if there is more string to the left only
            console.log("Found token on the right of the string.");
           substringsArray.push({
           value: element.substring(0, index), // compare these values using   find a match later
           indexFound: 0
            })
    } else if (index == 0 && substring.length < element.length) { // if there is     more string to the right only
            console.log("Found token on the left of the string.");
           substringsArray.push({
            value: element.substring(substring.length),
            indexFound: substring.length
           })
    } else { // the token is the only input
        console.log("The token consists of the entire string.");
    }
  } else if (regEx.test && element.length == 1) {
      var x = regEx.exec(element); // give us more information on the element
      var value = x["0"]; // keep track of the value of the token
      var index = x.index; // keep track of the index
      var substring = value;
        tokenList.push({
          value: value,
          index: index
        })
    } else {
      console.log("No match for regexp " + regEx + "trying the next one...");
      return;
  }
  console.log(tokenList);
  tokenList.sort(function(a, b) {
    return a.indexFound - b.indexFound;
  });
  console.log(tokenList);
  for (var i = 0; i < tokenList.length; i++) {
    if (tokenList[i].value.length > 1)
      findAMatch(tokenList[i].value);
    else
      findACharMatch(tokenList[i].value);
  }
};

【问题讨论】:

  • 该代码为我运行没有问题。
  • 我也没有发现问题,但可能是范围问题。此外,如果你总是使用 10 个元素,你可以做到 10 个,或者创建一个全局变量 var size = regexList.length;并迭代直到 i
  • 我也没有遇到问题,但我可能认为 failSafe 函数对您的数组有影响
  • 请发布 failSafe 功能,这不是“我们在猜测您未显示的功能做了什么”的游戏,而是“我们帮助您使用您显示的代码”的游戏。您显示的代码运行没有问题,因此应该关闭问题,因为您不清楚您在问什么。
  • 现在,请告诉我这一切都不是徒劳的 - 现在得出去吃晚饭了。

标签: javascript arrays regex


【解决方案1】:

好的,根据RegExp docs,我运行了你所有显示的代码,但它有一个错误

如果匹配失败,exec()方法返回null。

因此,在您的代码中,您总是理所当然地认为regEx.exec(element); 将返回一个数组(它假设 RegExp 将匹配至少一个元素),至少在您的示例中,它是错误的,而您是不处理。

简而言之,摆脱这种情况的最简单方法是在x 为空时返回:

var x = regEx.exec(element);
if (!x) return // add this

测试了一下,没有抛出任何问题,只有控制台输出为matched a

【讨论】:

    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2022-09-23
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    相关资源
    最近更新 更多