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

时间:2021-01-12 15:52:47

标签: javascript typescript group-by

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

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,在这些组中将是以下文本该行,直到下一次出现

因此结果输出将类似于以下内容,允许通过分组名称访问值

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

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

  • 找到“Checking against”并将其设置为键
  • 将每一行附加到下一次出现作为值

1 个答案:

答案 0 :(得分:0)

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

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

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);

相关问题