ssbecse
ssbecse

Reputation: 61

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.

Upvotes: 0

Views: 761

Answers (2)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

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

Upvotes: 2

OpenSauce
OpenSauce

Reputation: 8623

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.

Upvotes: 4

Related Questions