如何显示所有结果而不以第一场比赛结束?

如何显示所有结果而不以第一场比赛结束?此代码帮助我获取开始词和结束词之间的文本。但搜索在找到第一对后就结束了。您如何找到所有匹配项?


const file = fs.readFileSync('./history.txt', 'utf8')

const startString = '-----CompilerOutput:-stderr----------'

const endString = '-----EndCompilerOutput---------------'

const startIndex = file.indexOf(startString) + startString.length

const endIndex = file.indexOf(endString)

const between = file.slice(startIndex, endIndex)

console.log(between)


小唯快跑啊
浏览 98回答 1
1回答

函数式编程

我希望我理解正确const file = fs.readFileSync('./history.txt', 'utf8');const startString = '-----CompilerOutput:-stderr----------';const endString = '-----EndCompilerOutput---------------';var startIndex = file.indexOf(startString);while(startIndex > -1) {    // get index after '-----CompilerOutput:-stderr----------'    let start = startIndex + startString.length;// -----------------------------------// EDIT: WRONG --> let end = file.indexOf(endString);// Need to start searching for next occurence starting at index after the start// -----------------------------------    // get index before '-----EndCompilerOutput---------------'    let end = file.indexOf(endString, start);    // get the text between    console.log(file.slice(start, end));    // set startIndex to next index of '-----CompilerOutput:-stderr----------'    // if not found the startIndex value will be -1 so end of the while loop    startIndex = file.indexOf(startString, end + endString.length);}编辑:示例文件:-----CompilerOutput:-stderr----------test1-----EndCompilerOutput--------------------CompilerOutput:-stderr----------test2-----EndCompilerOutput---------------输出:test1test2
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript