简体   繁体   中英

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.

just put a break in there:

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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