【发布时间】:2021-10-19 19:34:57
【问题描述】:
概述:
我正在使用正则表达式来解析文本文档并创建 JSON 文档。该文档是从控制台日志中解析出来的。
似乎发生的事情是(regex_1_match && regex_2_match) 没有按预期工作。它似乎与 regex_1 匹配,并且看起来满足 regex_2 并将其保存在同一个数组中。
const fs = require('fs');
const filename = fs.readFileSync('test.txt').toString();
var regex_1 = /"Course([0-9.])"/g;
var regex_2 = /"(Name)"/g;
var regex_3 = /"(No Name)"/g;
var regex_1_match = filename.match(regex_1);
var regex_2_match = filename.match(regex_2);
var regex_3_match = filename.match(regex_3);
let testJSON = [];
//for each line item
for (let index = 0; index < filename.length; index++) {
if(regex_1_match && regex_2_match) {
testJSON.push({
Course: regex_1[index]
Name: regex_2[index]
});
}
}
fs.writeFileSync("parsed_test_doc",JSON.stringify(testJSON));
test.txt:
------------ Course1 ------------
------------ foo ------------
------------ Name ------------
------------ Course2 ------------
------------ foo ------------
------------ No Name ------------
------------ Course3 ------------
------------ Name ------------
------------ foo ------------
------------ Course4 ------------
------------ No Name ------------
------------ Course5 ------------
------------ foo ------------
------------ Name ------------
输出:
[{
"Course": "Course1",
"Name": "Name"
}, {"Course": "Course2",
"Name": "Name"
},{"Course": "Course3",
"Name": "Name"
},{"Course": "Course4",
},{{"Course": "Course5"
}
预期输出:
[{
"Course": "Course1",
"Name": "Name"
}, {
"Course": "Course2"
}, {
"Course": "Course3",
"Name": "Name"
}, {
"Course": "Course4"
}, {
"Course": "Course5",
"Name": "Name"
}]
【问题讨论】:
-
您确定您的
for循环正确吗?遍历字符串会遍历每个字符,而不是行 -
另外,
JSON.stringify()无法生成您的 "output",因为它不是有效的 JSON -
为什么你的正则表达式包含
"字符?它们不会出现在您的文本示例中 -
对不起,我没有验证我的测试示例,我将验证。它是我目前正在使用的非常简化的版本,你说得对,应该删除
"字符。我的开发版本中没有这个。
标签: javascript node.js json regex