[英]How can I search for multiple strings and stop when one is found?
So I have a piece of code, which takes a line from one text file and searches it in other text file.所以我有一段代码,它从一个文本文件中取出一行并在另一个文本文件中搜索它。 This is my code:
这是我的代码:
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);
My questions are:我的问题是:
A. How do I perform a search of multiple strings(str1,str2,str3) because it only does it for str1 and then stops. A. 我如何执行多个字符串(str1、str2、str3)的搜索,因为它只搜索 str1,然后停止。
B. How do I make the search stop when it finds a string, eg searchStream('base_output', str1); B. 如何在找到字符串时停止搜索,例如 searchStream('base_output', str1); -> str1 is found in text file, the search then stops and then it moves to str2, then to str3 and writes the strings, for example, to another text file.
-> 在文本文件中找到 str1,搜索然后停止,然后移动到 str2,然后移动到 str3 并将字符串写入,例如,另一个文本文件。
A) When you read a line you can search for multiple strings one by one. A)当你阅读一行时,你可以一个一个地搜索多个字符串。 B) As we are using multiple
if
statements here rather than if else
the function searchs for each string one after another. B) 因为我们在这里使用多个
if
语句而不是if else
function 一个接一个地搜索每个字符串。 (PS you can read about writing to files in nodejs documentation) (PS,您可以在 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.