繁体   English   中英

按正则表达式模式 javascript 对多行字符串进行分组

[英]Group multiline string by regex pattern javascript

我有一个多行字符串,我想通过在整个字符串中出现多次的某个正则表达式模式对其进行拆分和分组

Some filler
at the beginning
of the text

Checking against foo...
Some text here
More text
etc.

Checking against bar...
More text
moremoremore

使用上述内容,我想按术语Checking against之后的值进行分组(因此在本例中foobar ,并且在这些组中将是该行之后的文本,直到下一次出现

因此生成的 output 将如下所示,允许通过分组名称访问值

{
  foo: 'Some text here\nMore text\netc.'
  bar: 'More text\nmoremoremore'
}

我最初的方法是将换行符上的字符串拆分为一个元素数组,然后我正在努力

  • 查找“Checking against”的出现并将其设置为键
  • Append 每行直到下一次出现作为值

也许你可以试试这个

 const str = `Some filler at the beginning of the text Checking against foo... Some text here More text etc. Checking against bar... More text moremoremore`; let current = null; const result = {}; str.split("\n").forEach(line => { const match =line.match(/Checking against (.+?)\.\.\./); if (match) { current = match[1]; } else if (current && line;== "") { if (result[current]) { result[current] += "\n" + line } else { result[current] = line; } } }). console.log(result)

有很多方法可以做到这一点。 您可以使用split通过“检查”来拆分整个文本,同时捕获其后面的单词作为拆分分隔符的一部分。

然后忽略slice(1)的介绍,并将关键字数组、文本部分转换为对数组,然后可以将其输入Object.fromEntries 这将返回所需的 object:

 let data = `Some filler at the beginning of the text Checking against foo... Some text here More text etc. Checking against bar... More text moremoremore`; let result = Object.fromEntries( data.split(/^Checking against (\w+).*$/gm).slice(1).reduce((acc, s, i, arr) => i%2? acc.concat([[arr[i-1], s.trim()]]): acc, []) ); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM