如何在字符串数组中使用正则表达式匹配?

时间:2016-07-01 07:02:26

标签: javascript arrays matching string-matching regexp-substr

我想这样:当输入的值与my数组的值匹配时,写下匹配值。

所以这是我的代码:

//我的数组如下:

var checkNames = (document.getElementById("KPIorCounterList").value.split("\n").map(element => element.trim())).filter(v=>v != "");

我的另一个数组:myarray= ["RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"]

例如;当写RAB *到textare时,我应该看到,从" RAB&#34开始;

我想,我的代码应该如下:

  for (var i = 0; i < checkNames.length; i++) {
                    for (var j = 0; j < myarray.length; j++) {
           // var str = myarray[j].split(" "); // I am not sure for his.

            I want to this for here : (pseudo code)
            for example checkName[i] == RAB*
            if (checkName[i].match("match condition") == myarray[j])
            alert(myarray[j]);
            //I should show output myarray[j] == RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"
       }
    }

我该怎么办? 请..

2 个答案:

答案 0 :(得分:1)

@eagle,我相信这是checkNames的输入。如果是这样,这是我的解决方案 -

var checkNames = ['RAB*'];
var myarray = ["RAB Video call drop %","RAB PS R99 drop % ","RAB PS HSDPA drop %"];

for (var i = 0; i < checkNames.length; i++) {
    for (var j = 0; j < myarray.length; j++) {
        var formatRegExpr = checkNames[i].replace('*','.*');
        var re = new RegExp(formatRegExpr, 'g');
        alert(myarray[j].match(re));
    }
}

如果它能解决您的要求,请接受此答案。

答案 1 :(得分:1)

function check(){
var checkNames = (document.getElementById("KPIorCounterList").value.split("\n").map(element => element.trim())).filter(v=>v != "");
var myarray = ["RAB Video call drop %", "RAB PS R99 drop % ", "RAB PS HSDPA drop %"]
for (var i = 0; i < checkNames.length; i++) {
  console.log("results for", checkNames[i])
  for (var j = 0; j < myarray.length; j++) {

      var matchString = myarray[j].match(new RegExp(checkNames[i].replace('*','.*')));
    if (matchString && myarray.indexOf(matchString[0])!==-1) {
      console.log(myarray[j]);
    }
    //I should show output myarray[j] == RAB Video call drop %",RAB PS R99 drop % ","RAB PS HSDPA drop %"
  }
}
  }
<textarea id="KPIorCounterList"></textarea>
<button onclick="check()">Check</button>