4

I've recently seen this stackoverflow question that excludes all catch statements with a specific word.

Regex find catch blocks without log

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

How would you do the opposite?

I've tried switching the negative lookaround part to a positive lookaround, but all that does is grab empty exceptions.

catch\s*\(\s*\w*\s+\w*\s*\)\s*\{(?:[^}](?=\blog\b))*\}

example:

catch (Exception e) 
{
    log.debug("word");
            //stuff
}

I want to find all instances of "log.debug"

Community
  • 1
  • 1
user
  • 43
  • 3

1 Answers1

3

You can use a positive lookahead like this:

catch\s*\(\s*\w*\s+\w*\s*\)\s*\{(?=[^\}]*\blog\b)[^\}]+\}

(?=[^\}]*\blog\b) this checks if there's any log in that catch block and match only if there's the word log.

If you want to find log.debug, you simply edit the regex to:

catch\s*\(\s*\w*\s+\w*\s*\)\s*\{(?=[^\}]*\blog\.debug\b)[^\}]+\}
Jerry
  • 70,495
  • 13
  • 100
  • 144
  • I'm not sure if this should be a new question, but after finding all instances of logger.debug, how would you replace it with logger.error in eclipse? Not too sure how the $ symbol works in regex. – user Oct 04 '13 at 21:35
  • @user Is there a specific language/regex engine you're using? If you're using PCRE engine, you can do something like [this](http://regex101.com/r/gQ8cU5). Otherwise if `\G` and `\K` are not supported, I think it might be best to extract the whole catch block and carry out a full replace on it. `.NET` can make use of variable width lookbehinds, which I think would make it easier than PCRE. But I don't think that javascript/java/python can do this in a single regex is there are other code blocks (which are not catch blocks) around. – Jerry Oct 05 '13 at 11:11
  • I'm using eclipse's regex function in the search module. I don't believe it supports /K. Thanks for the help though! – user Oct 07 '13 at 14:01
  • @user Hey, it might be possible if you wrap the catch block around some special characters you won'd find the file. I don't know, let's say that `~` never appears in the file, you can use a first regex to put `~` before `catch` (like `~catch`) and after the closing brace (like `}~`) for those blocks having the `log.debug` in. Then, use a regex with a lookahead to replace all the `log.debug` inside. After which, you use a last replace to remove the `~` in the file. – Jerry Oct 07 '13 at 15:40