【问题标题】:How can I search for multiple strings and stop when one is found?如何搜索多个字符串并在找到一个时停止?
【发布时间】:2021-10-05 01:03:38
【问题描述】:

所以我有一段代码,它从一个文本文件中取出一行并在另一个文本文件中搜索它。这是我的代码:

const searchStream = (filename, text) => {

    return new Promise((resolve) => {
        const inStream = fs.createReadStream(filename + '.txt');
        const outStream = new stream;
        const rl = readline.createInterface(inStream, outStream);
        const result = [];
        const regEx = new RegExp(text, "i")
        rl.on('line', function (line) {
            if (line && line.search(regEx) >= 0) {
                result.push(line)
            }
        });
        rl.on('close', function () {
            console.log('finished search', result)
            resolve(result)
        });
    })
}
searchStream('base_output', str1);
searchStream('base_output', str2);
searchStream('base_output', str3);

我的问题是:

A.我如何执行多个字符串的搜索(str1,str2,str3),因为它只对 str1 进行搜索然后停止。

B.如何在找到字符串时停止搜索,例如searchStream('base_output', str1); -> str1 在文本文件中找到,搜索然后停止,然后移动到 str2,然后到 str3 并将字符串写入,例如,另一个文本文件。

【问题讨论】:

    标签: javascript node.js fs readline


    【解决方案1】:

    A) 当您阅读一行时,您可以一个一个地搜索多个字符串。 B) 由于我们在这里使用多个if 语句而不是if else,因此该函数一个接一个地搜索每个字符串。 (P.S. 你可以在 nodejs 文档中阅读关于写入文件的内容)

    const searchStream = (filename, text, text2, text3) => {
        return new Promise((resolve) => {
            const inStream = fs.createReadStream(filename + '.txt');
            const outStream = new stream;
            const rl = readline.createInterface(inStream, outStream);
            const result = [];
            const regEx = new RegExp(text, "i")
            const regEx2 = new RegExp(text2, "i")
            const regEx3 = new RegExp(text3, "i")
            rl.on('line', function (line) {
                if (line && line.search(regEx) >= 0) {
                    result.push(line)
                }
                if (line && line.search(regEx2) >= 0) {
                    result.push(line)
                }
                 if (line && line.search(regEx3) >= 0) {
                    result.push(line)
                }
            });
            rl.on('close', function () {
                console.log('finished search', result)
                resolve(result)
            });
        })
    }
    searchStream('base_output', str1, str2, str3);
    

    【讨论】:

    • 谢谢,工作正常!
    猜你喜欢
    • 2021-03-16
    • 2020-06-25
    • 2020-05-07
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多