如何用RegEx解析术语定义文本以生成闪卡(JavaScript环境)
用JavaScript正则解析术语-定义格式生成闪卡数据
核心实现代码
const input = `term(1)-def(1) term(2)-def(2) term(3)-def(3) term(4)-def(4) term(5)-def(5)`; const terms = []; const definitions = []; // 匹配每行的术语和定义,仅分割第一个'-' const lineRegex = /^([^-]+)-(.*)$/gm; let matchResult; // 遍历所有匹配行 while ((matchResult = lineRegex.exec(input)) !== null) { terms.push(matchResult[1]); definitions.push(matchResult[2]); } // 输出目标格式 console.log(`terms = ${JSON.stringify(terms)};`); console.log(`definitions = ${JSON.stringify(definitions)};`);
正则表达式说明
/^([^-]+)-(.*)$/gm 的各部分作用:
^:匹配每行的起始位置(配合m多行模式生效)([^-]+):捕获组1,匹配任意数量非-的字符——因为术语中不会出现-,所以这部分就是完整的术语内容-:精确匹配第一个分隔用的-(.*):捕获组2,匹配-之后的所有字符(包括定义中可能存在的-)$:匹配每行的结束位置(配合m多行模式生效)gm:修饰符,g表示全局匹配所有行,m表示多行模式(让^和$适配每行首尾,而非整个输入的首尾)
执行逻辑
- 通过
exec()循环遍历输入文本的所有匹配行 - 每次匹配中,
matchResult[1]对应术语,matchResult[2]对应定义,分别推入对应数组 - 最终生成的
terms和definitions数组完全符合需求
内容的提问来源于stack exchange,提问作者user17400329
相关产品推荐
相关产品推荐

