简体   繁体   English

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

[英]Javascript convert text to object with regex

I have the following text taken from a email body, I want to save each block into a object, then add into a array. 我从电子邮件正文中获取以下文本,我想将每个块保存到一个对象中,然后添加到一个数组中。 but I am struggle to correctly define the for loop, in another word how to seprate the blocks 但是我很难正确定义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................

In Javascript (Jquery can not be supported) 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})
}

I am basiclly Struggle to define the reg expression. 我基本上是在努力定义reg表达式。 any help would be much appriciated. 任何帮助将不胜枚举。

You should be able to separate the blocks by calling split() on the string and passing the appropriate separator. 您应该能够通过在字符串上调用split()并传递适当的分隔符来分隔块。 After this you can split it into lines, and then key/value pairs. 之后,您可以将其分成几行,然后是键/值对。

Of course, if your data is not consistent you will need to adjust, but something like this might get you started: 当然,如果您的数据不一致,则需要进行调整,但是像这样的方法可能会让您入门:

 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) 

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

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