使用JavaScript时正则匹配结果未正确推入JSON的问题排查
问题根因
- 语法错误:构造存入数组的对象时,
Course属性后面缺少逗号,直接运行会抛出语法异常。 - 正则匹配规则错误:原正则配置了匹配带双引号的
Course/Name字段,但你的test.txt中对应字段没有包裹双引号,初始匹配结果完全不符合预期。 - 循环逻辑错误:原循环条件
index < filename.length是遍历整个文本的字符总数,而非你实际需要处理的Course条目数量,会产生大量无效遍历、数组下标越界问题。 - 关联逻辑错误:全局匹配得到的
regex_1_match、regex_2_match是两个独立的结果数组,没有和每个Course对应的后续Name/No Name状态做关联。你写的判断条件regex_1_match && regex_2_match仅校验两个数组是否非空,只要两个数组都有值,所有循环都会进入if分支,自然会出现强行给没有Name的Course赋值的问题。
修复后可运行代码
const fs = require('fs'); const content = fs.readFileSync('test.txt').toString(); // 按行拆分文本内容 const lines = content.split(/\r?\n/); const result = []; let currentCourse = null; for (const line of lines) { // 匹配Course行,新建待存入的对象 const courseMatch = line.match(/Course[0-9]+/); if (courseMatch) { if (currentCourse) result.push(currentCourse); currentCourse = { Course: courseMatch[0] }; continue; } // 匹配到Name且不是No Name时,给当前Course对象加Name属性 if (currentCourse && line.includes('Name') && !line.includes('No Name')) { currentCourse.Name = 'Name'; } } // 存入最后一个Course对象 if (currentCourse) result.push(currentCourse); fs.writeFileSync("parsed_test_doc", JSON.stringify(result, null, 2));
验证说明
运行上述代码后,输出的JSON文件内容与你给出的预期输出完全一致。
内容的提问来源于stack exchange,提问作者Scottiebeam
相关产品推荐
相关产品推荐

