如何使用另一个字符串作为模板从字符串中提取数据?

时间:2012-09-08 17:59:45

标签: javascript regex

我正在寻找一种使用另一个字符串作为模板从字符串中一般提取数据的有效方法。伪代码:

var mystring = "NET,1:1,0,ipv4,192.168.1.7,255.255.255.0,192.168.1.1";
var mytemplate = "NET,[address],[lock_state],[ip_type],[ip],[netmask],[gateway]";
var result = mysteryMethod(mystring,mytemplate);
result:
    {
      address: '1:1',
      lock_state: '0',
      ip_type: 'ipv4',
      ip: '192.168.1.7',
      netmask: '255.255.255.0',
      gateway: '192.168.1.1'
    }

在这种情况下有一个逗号分隔符,但并非所有字符串都将被分隔或具有不同的分隔符。要解析的字符串都不包含括号。这与正则表达式有可能和/或明智吗?在这种情况下,速度至关重要。一如既往,非常感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

一个解决方案是http://jsfiddle.net/CrossEye/Kxe6W/

var templatizedStringParser = function(myTemplate, myString) {

    var names = [];
    var parts = myTemplate.replace( /\[([^\]]+)]/g, function(str, name) {
        names.push(name);
        return "~";
    }).split("~");

    var parser = function(myString) {
        var result = {};
        remainder = myString;
        var i, len, index;
        for (i = 0, len = names.length; i < len; i++) {
            remainder = remainder.substring(parts[i].length);
            index = remainder.indexOf(parts[i + 1]);
            result[names[i]] = remainder.substring(0, index);
            remainder = remainder.substring(index);
        }
        result[names[names.length - 1]] = remainder;
        return result;
    };

    return myString ? parser(myString) : parser;
};

您可以像这样使用

console.log(templatizedStringParser(myTemplate, myString));

或者这个:

var parser = templatizedStringParser(myTemplate);
console.log(parser(myString));

当我匆忙做这件事的时候,几乎可以肯定有一些瑕疵。使用“〜”可能对您不起作用。如果你有边界问题,可能还有其他问题,但它可能涵盖很多情况。

答案 1 :(得分:1)

//This method obtains each lable in the template string
function getLables(patt, templateStr) {
    var i = 0;
    var tmp = patt.exec(templateStr);
    var lables = new Array();
    while(tmp) {
        lables[i] = new String(tmp).replace("[", "").replace("]", "");
        tmp = patt.exec(templateStr);
        ++i;
    }
    return lables;
}

function extract(_inputStr, _template) {
    //Supposing the start string in template is NET
    var startStr = "NET";
    var inputStr = _inputStr.replace(startStr, "");
    var template = "";

    //You can add a control on the correctness of the template
    if(_template.indexOf(startStr) != 0) {
        return false;
        //you could use a throw clausole, in order to use exceptions
    } else {
        template = _template.replace(startStr, "");
    }

    var patt = /\[[a-z | _]+\]/ig; //Pattern to recognize each [lable]
    var delim = template.replace(patt, "[]").split("[]"); //Delimiter list
    var lable = getLables(patt, template); //Lables list
    var result = new Object();

    var endIndex;
    for(var i=0; i<lable.length; ++i) {
        inputStr = inputStr.replace(delim[i], "");
        endIndex = inputStr.indexOf(delim[i+1]);

        if( (i+1) == lable.length ) {
            result[lable[i]] = inputStr.substring(0, inputStr.length);
        } else {
            result[lable[i]] = inputStr.substring(0, endIndex)
            inputStr = inputStr.replace(result[lable[i]], "");
        }

    }

    return result;
}

在这个例子中:

var template = "NET???[one]/[two]";
var inputStr = "NET???test/8";

JSON.stringify(extract(inputStr, template));

结果是:

{
    "one":"test",
    "two":"8"
}