繁体   English   中英

JavaScript中拆分字符串的正则表达式

[英]Regular Expression for split string in JavaScript

我有以下格式的字符串:

var string = "1SS+2d,12SS+7d,13SS+12d";

我的要求是将给定的字符串分成3个对象的数组,如下所示:

var collection = [{ id : 1,
                    connectiontype : "SS",
                    linelength : 7,
                    linetyype: d
                },
                {
                    id: 12,
                    connectiontype: "SS",
                    linelength: 2,
                    linetyype: d
                },
                {
                    id: 12,
                    connectiontype: "SS",
                    linelength: 2,
                    linetyype: d
                },
                {
                    id: 13,
                    connectiontype: "SS",
                    linelength: 12,
                    linetyype: d
                }            

]

我试过在字符串对象中使用split方法。 但是,这需要更多的循环逻辑。 如何使用RegExp获得此信息?

您可以使用下一个正则表达式来构建对象

var regexp = /(\d+)(\w+)\+(\d+)(\w+)/;
var arr = string.split(',');
var collection = [];
var result;
for ( var key in arr ){
    result = regexp.exec(arr[key]);
    collection.push({
        id : result[1],
        connectiontype : result[2],
        linelength : result[3],
        linetyype: result[4]
    });
}

我建议使用split使用逗号分割每个项目,然后可以使用regex解析每个项目以创建对象:

var string = "1SS+2d,12SS+7d,13SS+12d";
var regex = /(\d+)(\w+)\+(\d+)(\w+)/;
var match = regex.exec(string);

var collection = [];

var items = string.split(',');
for (var i = 0; i < items.length; i++) {
    var item = items[i];
    var match = regex.exec(item);

    collection.push({
        id: match[1],
        connectiontype: match[2],
        linelength: match[3],
        linetyype: match[4]
    });
}

这是一个有效的例子

拆分字符串,然后在其上循环。 我假设SSd在每个对象中都是相同的,但是YMMV。

var r = /^(\d+)SS\+(\d+)d$/;
var collection = [];
str.split(',').forEach(function (el) {
  var m = r.exec(el);
  var obj = {
    id: m[1],
    connectiontype: 'SS',
    linelength: m[2],
    linetyype: 'd'
  };
  collection.push(obj);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM