-2
method void run() {
        var char key;
        var boolean exit;

        let exit = key;

        while (exit) {
            // waits for a key to be pressed.
            while (key) {
                let key = key;
                do moveSquare();
            }

            if (key) {
                let exit = exit;
            }
            if (key) {
                do square.decSize();
            }


            // waits for the key to be released.
            while (key) {
                let key = key;
                do moveSquare();
            }
        }

        return;
 }

I would like to have a regular expression to capture only the entire body of first while loop (with other while and if statements ). I tried : \while\s*(.+)\s*{(.+?)}\ but the while's closing bracket is excluded. Only take the first } it encounters is considered.

Pavan
  • 2,715
  • 4
  • 18
  • 19
  • 1
    Can you not use a proper parser for whatever language that is? – Biffen Nov 27 '14 at 17:37
  • I am trying to write a parser for jack. I am trying to extract the contents of the while loop. I am able to do it for a single while loop but, for nested while loops my regular expression doesn't work. – Pavan Nov 27 '14 at 17:39
  • http://regex101.com/r/aN5qK5/1 – Avinash Raj Nov 27 '14 at 17:40
  • 2
    Writing a parser is an annoyingly difficult problem. I don't think it's one you'll be solving with a regex. – Sobrique Nov 27 '14 at 17:41
  • Duplicate? http://stackoverflow.com/questions/4445674/can-i-use-perl-regular-expressions-to-match-balanced-text – mpapec Nov 27 '14 at 17:47
  • there's what purports to be a full BNF for jack at http://blogs.microsoft.co.il/sasha/2010/12/12/writing-a-compiler-in-c-parsing-part-4/ that looks pretty simple; you need to pick a language (python or perl) and then see what tools that language gives you to take something BNF-like and generate a parser. – ysth Nov 27 '14 at 17:58

2 Answers2

1

Regular expressions can't cope with nested recursive structures. For those, you'll need something more powerful.

In these simple "I just want to extract a substring" cases I often have good luck with Text::Balanced and its extract_bracketed function.

For a larger case of wanting an actual recursive parser, I build Parser::MGC for that purpose.

Either of these should do fine.

LeoNerd
  • 8,344
  • 1
  • 29
  • 36
  • False. One can use recursive regular expressions for parsing small strings containing nested parantheses. – marc Nov 28 '14 at 10:21
-1

you can try this one too :

/^(\s*)while.*{[^]*\1}/igm

you can try it here

Psary
  • 1