1

I wanted to search all the for loop within the for loop condition in my code.I have created regrex for that.

for?\(.*?;.*?;.*?\).*\s*for?\(.*?;.*?;.*?\)

This works for code like :

for(int i=0; i<StartTags.length; i++){
        for(int j=0; j<StartTags.length; j++){

but doesn't work for

for(;;) 
    {
        somecode;
            for(;;)
            {
                someOtherCode;
            }
    }

what should I add in regrex to make it work ?

I want to put some regrex instead of ".*\s*" so it will search multiline.

for?\(.*?;.*?;.*?\).*\s*for?\(.*?;.*?;.*?\)
roeygol
  • 4,908
  • 9
  • 51
  • 88
sahadev
  • 29
  • 2
  • 13

1 Answers1

2

First of all you can simplify your regex to:

for?\(.*;.*;.*\).*\s*for?\(.*;.*;.*\)

You see ".*" means: any occurrence of any char. Adding a "?" means: at least one time. any times one time ... as said: doesn't make sense.

But beyond that: I simply advise to separate your two cases.

Beyond that: your current pattern looks for

  1. for construct
  2. whitespaces
  3. for construct

And as you could have noticed yourself - the multiline part is working fine with that. Your current pattern already matches two lines fine. But of course it can not match your second example. Because your second represents

  1. for construct
  2. whitespaces
  3. somecode
  4. whitespaces
  5. for construct

In order to account for that, lets look at this:

for?\(.*;.*;.*\).*\s*.*\s*for?\(.*;.*;.*\)

In other words: for each line between those for constructs, you need one .*\s*

SO, for me

for?\(.*;.*;.*\).*\s*.*\s*.*\s*for?\(.*;.*;.*\)

matches your both your for loop constructs.

The problem here: if "somecode" would be two lines, you need to again put another "line-content-matcher" entry into the regex.

I tried

for?\(.*;.*;.*\)(.*\s*)*for?\(.*;.*;.*\)

but at least for me, that crashes eclipse.

(which doesn't come as surprise, as this question makes it clear that "counting", aka "indefinite" structure can not work with regular expressions)

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • .*?; is not the issue. for?\(.*?;.*?;.*?\) is searching perfectly. issue is i want to search two for loops. In between can be anything including newline. – sahadev Jan 25 '17 at 11:49
  • I found some kind of solution; I hope it is helpful enough for you to accept my answer and reward the time I put in here ;-) – GhostCat Jan 26 '17 at 08:20
  • and yes it crashes eclipse. :P – sahadev Feb 16 '18 at 09:50