简体   繁体   English

在Java中,如何将日志消息与多个字符串模式匹配

[英]in java, how to match the log message with more than one String pattern

i have several String patterns: 我有几种字符串模式:

ArrayList<String> tmp = new ArrayList<String>();
tmp.add("INFO");
tmp.add("Error");
tmp.add("Debug");
tmp.add("Failed");
tmp.add("Unable");

also i am checking the every lines in the file whether lines are matched with any one of the string pattern.if matched,i will display the line.my code is, 我也正在检查文件中的每一行是否行与任何字符串模式都匹配。如果匹配,我将显示行。我的代码是,

for (String pattern : tmp) {
    if (line.contains(pattern)) {
    System.out.println(line);
    }
}

Now the problem is,if line match with more than one string pattern,line gets displayed by every time whenever gets matched. 现在的问题是,如果线匹配有多个字符串模式,则每当匹配时,线都会被显示。

i want to display the line by only one time(need to check any of the string patterns are matched with line).How to do this. 我只想显示一行(需要检查任何字符串模式是否与line匹配)。如何执行此操作。

just put a break in there: 只是在那里break一下:

for (String pattern : tmp) {
 if (line.contains(pattern)) {
   System.out.println(line);
   break;
  }
}

Also, please properly format your code (indent it with 4 spaces), as it makes it easier to read. 另外,请正确格式化您的代码(将其缩进4个空格),以使其更易于阅读。

Use a regular expression: 使用正则表达式:

Pattern pattern = Pattern.compile("INFO|Error|Debug|Failed|Unable");
for(String line : lines){
    if(pattern.matcher(line).find()){
        System.out.println(line);
    }
}

This will print every line that contains one or more of the supplied keywords. 这将打印包含一个或多个提供的关键字的每一行。

See the Regular Expression Tutorial for more info. 有关更多信息,请参见正则表达式教程

Also, you could further improve this if you let the regex engine do the line splitting instead of passing individual lines: 另外,如果让正则表达式引擎执行行拆分而不是传递单独的行,则可以进一步改善此设置:

Pattern pattern = Pattern.compile("^.*(?:INFO|Error|Debug|Failed|Unable).*$",
                                  Pattern.MULTILINE);
Matcher matcher = pattern.matcher(theWholeSourceText);
while(matcher.find()){
    System.out.println(matcher.group());
}

Update: Ok, if the pattern is dynamic you can just build it dynamically from your list: 更新:好的,如果该模式是动态的,则可以从列表中动态构建它:

StringBuilder sb = new StringBuilder();
sb.append("^.*(?:");
Iterator<String> it = patternsList.iterator();
if(it.hasNext())sb.append(it.next());
while(it.hasNext())sb.append('|').append(it.next());
sb.append(").*$");
Matcher matcher = Pattern.compile(sb.toString(), Pattern.MULTILINE)
                         .matcher(theWholeSourceText);
while(matcher.find()){
    System.out.println(matcher.group());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM