Javascript使用正则表达式将文本转换为对象

时间:2018-04-03 19:12:42

标签: javascript regex

我从电子邮件正文中获取了以下文本,我想将每个块保存到一个对象中,然后添加到一个数组中。但我很难正确定义for循环,换句话说如何分割块

Name: Andy
Computer: ABC
IP: 192.168.0.1
Added By: Maria
Timestamp: 2018-03-15 08:45:08 +0000 UTC

Name: Richard
Computer: CDE
IP: 192.168.0.2
Timestamp: 2018-03-15 08:45:08 +0000 UTC

..........more blocks................

Javascript (无法支持Jquery)

//I first define a array  
var msgs= [];

//then define a object
var msg= {
    Name:"",
    Computer:"",
    IP:50,
    TimeStamp: new Date()
};

var reg = (.....);
var result;

//wholeMsgBody is the whole text sample I have provided
while((result = reg.exec(wholeMsgBody)) !== null) {
  //assume the block = Name:.... until TimeStamp.....
  var userName = block.match(Name:.*); //Andy
  var computer = block.match(Computer:.*); //ABC
  var ip = block.match(Computer:.*) //192.168.0.1
  Var timeStamp = new Date(block.match(Timestamp:.*)) //2018/03/15

  msgs.push({"Name":userName, "Computer":computer, "ip":ip, "timeStamp":timeStamp})
}

我基本上是在努力定义reg表达式。任何帮助都会很有帮助。

1 个答案:

答案 0 :(得分:2)

您应该能够通过调用字符串上的split()并传递适当的分隔符来分隔块。在此之后,您可以将其拆分为行,然后键入/值对。

当然,如果你的数据不一致,你需要调整,但是这样的事情可能会让你开始:

var str = `Name: Andy
Computer: ABC
IP: 192.168.0.1
Added By: Maria
Timestamp: 2018-03-15 08:45:08 +0000 UTC

Name: Richard
Computer: CDE
IP: 192.168.0.2
Timestamp: 2018-03-15 08:45:08 +0000 UTC
`

var blocks = str.split('\n\n')
var objects = blocks.map(b => {
    let lines = b.split('\n')
    return lines.reduce((obj, line) => {
        if (!line) return obj
        let [key, value] = line.split(/:(.+)/)
        obj[key] = value.trim()
        return obj
    }, {})

})
console.log(objects)