如何用regex或NodeJS将含+量级分隔符的文本转为指定CSV格式
实现方案
你可以直接用Node.js实现,核心逻辑是逐行拆分+正则匹配不同量级的关键词块,完整代码如下:
const input = `03.12.2020 ++++baz;bar;++bik; 04.12.2020 +++bar; 05.12.2020 ++++baz;bar;bur,jojo;+++bik;buch;+pac;` // 按行拆分,过滤空行 const lines = input.split('\n').filter(line => line.trim()) const output = [] lines.forEach(line => { // 拆分日期和后面的关键词段 const [date, keywordPart] = line.split(/\s+/, 2) // 匹配所有 +开头的量级块 const magMatches = keywordPart.matchAll(/(\+)(\+*)([^+]*)/g) for (const match of magMatches) { // 计算量级:+号的总数量 const magnitude = 1 + match[2].length // 拆分关键词,过滤空字符串 const keywords = match[3].split(';').filter(k => k.trim()) keywords.forEach(keyword => { output.push(`${date}, ${keyword}, ${magnitude}`) }) } }) // 打印结果 console.log(output.join('\n'))
运行输出
03.12.2020, baz, 4 03.12.2020, bar, 4 03.12.2020, bik, 2 04.12.2020, bar, 3 05.12.2020, baz, 4 05.12.2020, bar, 4 05.12.2020, bur,jojo, 4 05.12.2020, bik, 3 05.12.2020, buch, 3 05.12.2020, pac, 1
内容的提问来源于stack exchange,提问作者pall04
相关产品推荐
相关产品推荐

