[英]Read txt file by searching for a word and also retrieve the lines of the found word and also count the lines of the found word - Possible?
我在這里發布了一個問題,但我仍然堅持
是我的txt:
Toto1 The line Toto2 The line Toto3 The line Toto2 The line (second) Toto3 The line (second) ...
當我搜索“ Toto2”時,有必要恢復包含“ Toto2”的每一行,並且也有必要計算包含“ Toto2”的行數,這可能嗎?
var regex = new RegExp('Toto2.*\\n', 'g');
有了這個,我們將不得不返回:
Toto2 The line Toto2 The line (second)
和其他變量:
2
謝謝
您可以使用帶有簡單正則表達式的Array.prototype.filter
:
const text = `Toto1 The line Toto2 The line Toto3 The line Toto2 The line (second) Toto3 The line (second)`; const filteredLines = text.split('\\n').filter(line => /Toto2/gi.test(line)); const count = filteredLines.length; console.log(filteredLines); console.log(count);
獲取具有相應行號的行(借助Array.prototype.reduce
)
const text = `Toto1 The line Toto2 The line Toto3 The line Toto2 The line (second) Toto3 The line (second)`; const linesWithIndexes = text.split('\\n').reduce((all, line, i) => { return all.concat(/Toto2/gi.test(line) ? {line, lineNumber: i + 1} : []); }, []); console.log(linesWithIndexes);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.