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

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.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'
    }

There is a comma delimiter in this case but not all strings will be delimited or will have different delimiters. None of the strings to be parsed will contain brackets. Is this possible and/or wise to do with regular expressions? Speed is crucial in this case. As always, your help is much appreciated.

Answers


One solution is at 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;
};

You can use it like this

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

or this:

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

There is almost certainly some cruft in there as I did this in a hurry. The use of the "~" might not work for you. And there are likely other problems if you have boundary issues, but it might cover many cases. ‚Äč


Need Your Help

Suppress the list item marker for an <li> element

css

How can I suppress the list item marker for a list element using only css?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.