-1

I'm trying to make a java project where i will be taking a log file (txt file) of data entries and a regular expression file (also txt and contains RE rules). My goal is to take each rule (RE) and run it through the log file and find matches, the end goal is to print the number of matches i found. The code is supposed to be generic meaning that i dont care what the regular expressions are, i just a function that takes 2 parameters, a regular expression and a string line from the log file. I found out that i can use the regex class (using the pattern and matcher class). So my program consists of 2 nested for loops and the steps are as follows: 1- store first regular expression from the rules file. 2- compare the rule with every line in the log file using the pattern and matcher class. 3- if a match is found i increment a counter. nb: aside from the nested loops. my problem is if for example the rule is "notifications" and the log line is "[INFO ] 2020-05-28 09:13:38.965 notifications [main] [CommonEventsManager.initialize] - Initialization for module [Common] was successful..." i should get a match but the result is false. this is the code im using to match :

  • Pattern p = Pattern.compile("notifications");
  • Matcher m = p.matcher( "[INFO ] 2020-05-28 09:13:38.965 notifications [main] - [CommonEventsManager.initialize] - Initialization for module [Common] was successful..."); -System.out.println("dsds "+ m.matches());

So how can i use regex to find matches without having to worry about the regular expression format

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • 1
    `Matcher::matches` returns `true` if the _entire_ `String` matches your regex. It doesn't. You could try `Matcher::find` and iteratively count (or in java 9+ use `Matcher::results::size`). – BeUndead Sep 16 '20 at 14:33
  • You can surround your expression with `.*` (both sides) to make it match or simply use String.contains("notifications"); – dimitar.yanev Sep 16 '20 at 14:43

1 Answers1

-1

You get no match since Matcher::matches() returns true only if the regex matches the entire string.

In order to achieve what you have described, you have several options. For Java 8 (or earlier), if you want to use a pattern:

Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(logFileContent);
int count = 0;
while (m.find()) {
    count++;
}

For Java 9+, if you want to use a pattern:

Pattern p = Pattern.compile(regex);
long count = p.matcher(logFileContent).results().count();

If you want to keep it shorter, you could use (some might say abuse) String::split():

int count = logFileContent.split(regex).length - 1;
hedengran
  • 53
  • 4