计算正则表达式数组的长度

时间:2017-02-28 22:32:04

标签: javascript arrays regex

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

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:无法读取我的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);
  }
};

1 个答案:

答案 0 :(得分:0)

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

  

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

因此,在您的代码中,您始终认为regEx.exec(element);将返回一个数组(它假设RegExp将匹配至少一个元素),这至少在您的示例中是假的,并且你没有处理它。

简而言之,解决这个问题的最简单方法是在x为空时返回:

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

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