簡體   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