The best place to ask programming/development questions, imo. UPDATE: stackoverflow is the *worst* place to *ask* questions (if your first question/comment doesn't get any up-rating/response, then u can't ask anymore questions--ridiculously unrealistic), but a great reference for finding answers.

My Music (Nickleus)

20121114

regex to find nested/embedded for loops in java

most say it is impossible to make a failsafe regexp for finding nested for loops, but here's something i came up with that is somewhat close:
for\s*\((?:[\s\S](?!private|public))+?for\s*\(

this will find nested for loops when they occur, but the drawback is that it will also match multiple instances of for loops within methods defined as either private or public (if you have methods that begin with other modifiers [e.g. protected], you can add those too). e.g. it will match code like this:
############
for(List<String> c2 : c){
    int counter = 0;
    for(
String str : c2){
        s += buildFragment(counter, (str));
    }
}
############
for(int i = 0; i < x.size(); i++){
...
}

if(i2 != null){
    for(
int y = 0; y < z.size(); y++){
############

i'll try to explain the regex for you:
for\s*\(

start matching when you find the beginning of a for loop.
\s* means zero or more whitespace between for and (
to match a literal left parenthesis you need to escape it with a backslash: \(

(?:[\s\S](?!private|public))+

match 1 or more ( + ) of any character ( [\s\S] ) that isn't ( ?! ) followed directly by the words private OR ( | ) public,

?for\s*\(

and stop after the first instance ( ? ) of a match for the beginning of another for loop ( for\s*\( ).

No comments:

Post a Comment