How can I extract data from a string using another string as a template?

后端 未结 2 1646
半阙折子戏
半阙折子戏 2021-01-24 01:16

I am looking for an efficient way to generically extract data from a string using another string as a template. Pseudocode:

var mystring = \"NET,1:1,0,ipv4,192.1         


        
2条回答
  •  不思量自难忘°
    2021-01-24 01:50

    //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

    In this example:

    var template = "NET???[one]/[two]";
    var inputStr = "NET???test/8";
    
    JSON.stringify(extract(inputStr, template));
    

    The result is:

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

提交回复
热议问题