为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

小唯快跑啊 2023-08-05 19:33:21
如何显示所有结果而不以第一场比赛结束?此代码帮助我获取开始词和结束词之间的文本。但搜索在找到第一对后就结束了。您如何找到所有匹配项?const file = fs.readFileSync('./history.txt', 'utf8')const startString = '-----CompilerOutput:-stderr----------'const endString = '-----EndCompilerOutput---------------'const startIndex = file.indexOf(startString) + startString.lengthconst endIndex = file.indexOf(endString)const between = file.slice(startIndex, endIndex)console.log(between)
查看完整描述

1 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

我希望我理解正确


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

输出:


test1



test2


查看完整回答
反对 回复 2023-08-05
  • 1 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信