L
L
Leonid Fedotov2016-11-11 15:27:30
Java
Leonid Fedotov, 2016-11-11 15:27:30

How to make a regular expression that determines the level of nesting of loops?

For a program containing several nested loops, use regular expressions to determine the nesting level of loops.
those. how it works:
We feed the regular expression the code:

...
for(var i=0;i<10;i++){
    something();
    if(){
        ....
    }
  while(true){
    for(var i=0;i!=3;i++){
      ...
    }
  }
}
...

And it should return to us that the nesting is 3.
The program is written in JAVA, so it uses something like:
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
   i++;
}

Where i is the number of nesting matches

. As I understand it, we need something like
(for|while){(*^})(if{*})(*^})(for|while)
But in regular expressions I am weak and wrote nonsense, I need help :)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Rsa97, 2016-11-11
@Rsa97

Regular expression is not designed for computation and is not well suited for recursive nesting. IMHO, a lexical analyzer is needed here.

S
saltydogd, 2016-11-11
@saltydogd

As an option, combine the regular expression and its consistent application:
To obtain an "embracing" cycle (its body)
, then pull out the contents of the match, and apply the same pattern to it, depth +1, and so on. while the content is matched by regular match
Threat regular season from C#, I didn’t check it in Java, but I should be able to handle it

X
xmoonlight, 2016-11-11
@xmoonlight

Solutions (by task type, in ascending order of CPU load):
1. traversal of the "tree"
2. reverse Polish notation
3. regular expressions, reverse recursive lookup for a given match
Choose.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question