如何使用另一个字符串作为模板从字符串中提取数据? [英] How can I extract data from a string using another string as a template?

查看:217
本文介绍了如何使用另一个字符串作为模板从字符串中提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

一个解决方案是在 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));

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

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. ​

这篇关于如何使用另一个字符串作为模板从字符串中提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆