如何根据ID分割数据?

时间:2017-03-02 21:03:51

标签: javascript node.js

我正在从文件中读取数据,因此下面的代码将奇异行数据推送到results如何在以下情况ID中基于id分割数据。目标是获得该ID的完整数据,即使是多行。

Ctrl.js

  var results = [];
  var lines = data.split('\n'); // get the lines
            lines.forEach(function(line) { // for each line in lines
                if (line.indexOf(searchStr) != -1) { // if the line contain the searchSt
                    results.push({
                    filename:logfile.filename,
                    value:line
                    });
                }
            });

file.txt的

[ID:81d166ed-dcd6-4f30-bcf4-7c3c1a8feefb]testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting ind
[ID:8a3b2de6-742e-49e4-bf96-02d14e6b0799]testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry.
[ID:c3d19dfe-d803-4661-a0c4-52a18aa48766]testid Lorem test Ipsum is simply dummy

2 个答案:

答案 0 :(得分:0)

如果您的所有ID都是相同的长度,看起来就像它们一样,在您的行内。您可以将其用于提取ID。不完全确定你想要对其余部分做什么,但看起来它会抓住ID。

var id = line.substr(4,36)

解释,只是抓住分割中字符串中该位置的文本,看起来应该总是在同一个地方。有更强大的方法,但对于这种情况,它似乎是一个容易理解的例子。

答案 1 :(得分:0)

只需在foreach循环之前添加它:

for(var i = 0; lines.length > i ; i = i + 1){
    lines[i] = lines[i].replace(/\[ID:([a-z0-9]+-)+([a-z0-9])+\]/g, '');
}

它应该会产生一个没有[ID:value]的数组,对于你的例子,它将返回:

"testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting ind"
"testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry."
"testid Lorem test Ipsum is simply dummy"