Tzah Mama
Tzah Mama

Reputation: 1567

Searching multiple line text that doesn't contain certain expression

The way we log handled exceptions in our program is calling our Logger class on the catch block.

We found out that couple of our try/catch blocks are missing this logger. I want to create a regex to find out where are those blocks that contain a catch block without a calling the Logger class.

With my limited knowledge with regex I've came up with this:

catch[\s\S]+?{[\s\S]+?(?!log)[\s\S]+?}

But it seems that this one returns any catch block instead of those not containing the word 'log' inside of them.

What am I doing wrong / how can I fix my regex?

Edit

Wanted code (regex should not return this)

catch (SomeException e)
{
    Log(e);
}

Bad code (regex should return this)

catch (SomeException e)
{
    //Something
}

Upvotes: 0

Views: 44

Answers (2)

nu11p01n73R
nu11p01n73R

Reputation: 26667

A small change would help you

/catch[^{]+{(?![^}]+log)[^}]+}/i

Regex Demo

Changes made

  • Rather using [\s\S] lets be little be more specific using [^{] and [^}] which are negated character classes which wont match anything in the class.

  • move the [^}] into the look ahead. Now (?![^}]+log) ensures that there is no log within the catch block.

Upvotes: 2

vks
vks

Reputation: 67968

catch[^{]*{(?:(?!\blog\b|})[\s\S])*}

Try this with flag i or ignorecase.See demo.

https://regex101.com/r/sH8aR8/29

Upvotes: 0

Related Questions