Javascript模式匹配变量

时间:2012-07-13 01:39:52

标签: javascript design-patterns matching

我正在努力寻找一种方法来获得变量的模式匹配。我尝试过拆分和执行indexOf,使用match和switch(true)语句,但都没有成功。任何帮助将不胜感激!

currentExports = 'sec=sys,rw=badhost1.foo.com:badhost2.foo.com,root=badhost1.foo.com:badhost2.foo.com';
badExportHosts = params.badExportHosts.split(':');
for (badHost = 0; badHost < badExportHosts.length; badHost++) {
    if (!currentExports.match(/badExportHosts[badHost]/g)) {
        printf('Entry ' + badExportHosts[badHost] + ' was not found in ' + currentExports + '\n');
    } else {
        printf('Entry ' + badExportHosts[badHost] + ' was found in ' + currentExports + '\n');
    }

如果我进入我的表格:

badhost1.foo.com:badhost2.foo.com

我很遗憾地得到了这个结果:

Entry badhost1.foo.com was not found in sec=sys,rw=badhost1.foo.com:badhost2.foo.com,root=badhost1.foo.com:badhost2.foo.com
Entry badhost2.foo.com was not found in sec=sys,rw=badhost1.foo.com:badhost2.foo.com,root=badhost1.foo.com:badhost2.foo.com

我怎样才能匹配?

2 个答案:

答案 0 :(得分:0)

我认为你的意图似乎不够明确,但是,如果我理解正确,你想要的只是检查你的“badHost”字符串是否包含在currentExports的任何地方,你可以尝试替换它:

if (!currentExports.match(/badExportHosts[badHost]/g)) {

为此:

if (currentExports.indexOf(badExportHosts[badHost]) < 0) {

答案 1 :(得分:0)

你走在正确的轨道上。尝试使用RegExp这样的对象:

var pattern;
currentExports = //your same code goes here
//...
for(badHost = 0; badHost < badExportHosts.length; badHost++){
    pattern = new RegExp(badExportHosts[badHost], 'g');
    if (!currentExports.match(pattern)) {
        //your print statments go here
    }
}

问题是你对match()的调用确实试图在for循环的每次迭代中匹配字符串“badExportHosts [badHosts]”,这是不好的,因为你需要匹配值在badExportHosts数组中,而不是变量名本身。您需要/badhost1.foo.com/g这样的正则表达式,RegExp对象为您提供。