简体   繁体   中英

Group multiline string by regex pattern javascript

I have a multiline string that I want to split and group by a certain regex pattern that appears several times throughout the string

Some filler
at the beginning
of the text

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

Checking against bar...
More text
moremoremore

Using the above, I'd like to group by the value following the term Checking against (so in this example foo and bar , and in those groups would be the text following that line, up until the next occurrence

So the resulting output would be something like the below, allowing access to the values by the grouping name

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

My initial approach was to split the string on the newlines into an array of elements, I'm then struggling to

  • Find occurrence of "Checking against" and set that as the key
  • Append every line up until the next occurrence as the value

maybe you can try this

 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)

There are many ways to do that. You could use split to split the whole text by "Checking against" and at the same time capture the word that follows it as part of the splitting separator.

Then ignore the intro with slice(1) , and transform the array of keyword, text parts into an array of pairs, which in turn can be fed into Object.fromEntries . That will return the desired 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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