Return repeated groups only if above a certain number

45 views Asked by At

I'm setting up a regex to look for null pointer exceptions in logs. The regex for this is very simple:

(java\.lang\.NullPointerException)

And this returns three groups from my logs:

2020-01-31 00:00:01 - Searching for account details
Error:
java.lang.NullPointerException
2020-01-31 00:00:30 - Searching for account details
Error:
java.lang.NullPointerException
2020-01-31 00:00:50 - Searching for account details
Error:
java.lang.NullPointerException

What I would like to do is set this up to only return results if there is more than a certain number of matching groups. For example, (java.lang.NullPointerException){2,} should in theory return results for two or more groups, while {4,} should not match. So far, I've been reading up on using curly brackets for this, but I have not been able to get this to work with anything other than {1,} - everything else just returns no matches.

EDIT: Thanks to Pavel for the answer. I made a slight modification for my use case:

(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\s-\sSearching\sfor\saccount\sdetails\nError:\njava\.lang\.NullPointerException[\s\S]){10,}

This pattern is to match exactly that message from the date to the null pointer error. I also removed the * from [\s\S], to ensure that it only catches 10 consecutive errors. That way, if there is 10 or more instances of:

2020-01-31 00:00:01 - Searching for account details
Error:
java.lang.NullPointerException

it will return a match. But if there is something like:

2020-01-31 00:00:50 - Searching for account details
Error:
java.lang.NullPointerException
2020-01-31 00:00:50 - Searching for account details
Found something:
Hello world
2020-01-31 00:00:50 - Searching for account details
Error:
java.lang.NullPointerException

A match will not be returned, due to the hello world message between the messages. I did not think of this use case until after the fact, so I didn't include it in the original question.

1

There are 1 answers

3
Pavel Lint On BEST ANSWER

This works as you describe it:

(java\.lang\.NullPointerException[\s\S]*){2,}

See, you need to add [\s\S]* to the end so that it matches all the characters between the two exceptions including whitespaces.

Here's the demo: https://regex101.com/r/dnIgKs/1/