gpt4 book ai didi

java - 我需要搜索多个关键字

转载 作者:行者123 更新时间:2023-12-01 23:37:15 26 4
gpt4 key购买 nike

我需要扫描日志中的多个关键字 ERROR、OS、ARCH。下面的代码适用于单个关键字搜索

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ErrorScanner
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("Users/home/test.txt"));
boolean ifError = false;
while(s.hasNextLine())
{
String nextLine = s.nextLine();
if(nextLine.contains("ERROR"))
{
System.out.println("Failed" + " " + nextLine);
ifError = true;
}
}
if(! ifError)
{
System.out.println("Nothing found");
}
}
}

最佳答案

试试这个:

if (nextLine.contains("ERROR")
|| nextLine.contains("OS")
|| nextLine.contains("ARCH")) {
// ...
}

或者更复杂的解决方案,如果有很多关键字并且行很长,则很有用:

// declared before the while loop
Set<String> keywords = new HashSet<String>(Arrays.asList("ERROR", "OS", "ARCH"));

// inside the while loop
for (String word : nextLine.split("\\s+")) {
if (keywords.contains(word)) {
System.out.println("Failed" + " " + nextLine);
ifError = true;
break;
}
}

关于java - 我需要搜索多个关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18500625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com