-1

I want to find a block Using Regular expression. Here Used the below reg expression for finding try block which has only "logger.error("................")" and no business logic in the block. Please see the below code sample code reference

try[\s]\{((/\(.|[\r\n])?\/)|\s)*\}

So please provide how to find logger.error in the try block with explain.

Ex:

try {

System.out.println("......");
        /*
         * fsdsddgd ddgdgdfg gdfgdgdfg gdfgdfg fgdfgfg
         */

        /*
         * fsdsddgd ddgdgdfg gdfgdgdfg gdfgdfg fgdfgfg
         */
//single line comments
logger.error("................");

    }

Thanks in advance

KaviK
  • 625
  • 9
  • 18
  • Java code parsing another Java code, can you clarify what are you doing here? – anubhava Sep 09 '14 at 07:12
  • 1
    You can't reliably parse code with a single regular expression, just like you [can't reliably parse HTML with a single regular expression](http://stackoverflow.com/a/1732454/157247). You just can't. – T.J. Crowder Sep 09 '14 at 07:12
  • now i am finding the line logger.error("....") in the try block . I am trying to find using reg exp. So strugle with reg exp for above requirements. So please do need ful. – KaviK Sep 09 '14 at 07:15
  • You could use a loop and a flag to keep track of whether you are in a try block and then check. One regex, like TJ Crowder says, not possible. – TheLostMind Sep 09 '14 at 07:23
  • @KaviK What you're essentially trying to do is solve a differential equation, without calculus (or Laplace transformation). – Mikkel Løkke Sep 09 '14 at 07:23

2 Answers2

0

Because the {} can be nested theoretically indefinitely, you can't reliably match on that in regex. If you know for a fact that your try block has a catch (which it should have) you could match it with this monster of a regex (necessary to avoid matching the words try or catch when they're inside a string or comment).

You're code block would be inside capture group 2.

(['"])(?:(?!\1|\\).|\\.)*\1|\/\/[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*\*\/|(\btry\b(?:(['"])(?:(?!\3|\\).|\\.)*\3|\/\/[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*\*\/|(?:[^c]|\Bc|c(?!atch)|catch\B))*\bcatch\b)

Regular expression visualization

Debuggex Demo

asontu
  • 4,548
  • 1
  • 21
  • 29
0

As in the comments already stated, this can not be done with just a single RegEx. When I stumble across such tasks, I like to use AWK scripts.

/try/{
 //You found the start of a try block
 printLineNumber = true;
}

/logger\.error/{
 if(printLineNumber){
  print NR; //NR is an AWK field, that contains the current line number
 }
}

/catch/{
 //You found the end of a try block
 printLineNumber = false;
}

I did not tried this code, so it propably won't work right away. Google a bit for AWK, the basics can be learned pretty fast and it will help you in a lot of situations, not just this one task.

Korashen
  • 2,144
  • 2
  • 18
  • 28