简体   繁体   English

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

[英]Regular Expression for split string in JavaScript

I have the string in like below format: 我有以下格式的字符串:

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

My requirement is split the given string into array with 3 objects like in the following format: 我的要求是将给定的字符串分成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
                }            

]

I have tried with split method in string object. 我试过在字符串对象中使用split方法。 But it take more looping logic. 但是,这需要更多的循环逻辑。 How to obtain this using RegExp? 如何使用RegExp获得此信息?

you can use next regular expression to build your object 您可以使用下一个正则表达式来构建对象

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]
    });
}

I would recommend using split to split each item using comma, then you can use regex to parse each item to create the object: 我建议使用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]
    });
}

Here is a working example 这是一个有效的例子

Split the string then loop over it. 拆分字符串,然后在其上循环。 I've assumed that SS and d are going to be the same in each object but YMMV. 我假设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