Can regular expressions be used to match nested patterns? [duplicate]

No. It's that easy. A finite automaton (which is the data structure underlying a regular expression) does not have memory apart from the state it's in, and if you have arbitrarily deep nesting, you need an arbitrarily large automaton, which collides with the notion of a finite automaton.

You can match nested/paired elements up to a fixed depth, where the depth is only limited by your memory, because the automaton gets very large. In practice, however, you should use a push-down automaton, i.e a parser for a context-free grammar, for instance LL (top-down) or LR (bottom-up). You have to take the worse runtime behavior into account: O(n^3) vs. O(n), with n = length(input).

There are many parser generators avialable, for instance ANTLR for Java. Finding an existing grammar for Java (or C) is also not difficult.
For more background: Automata Theory at Wikipedia


Using regular expressions to check for nested patterns is very easy.

'/(\((?>[^()]+|(?1))*\))/'

Probably working Perl solution, if the string is on one line:

my $NesteD ;
$NesteD = qr/ \{( [^{}] | (??{ $NesteD }) )* \} /x ;

if ( $Stringy =~ m/\b( \w+$NesteD )/x ) {
    print "Found: $1\n" ;
  }

HTH

EDIT: check:

  • http://dev.perl.org/perl6/rfc/145.html
  • ruby information: http://www.ruby-forum.com/topic/112084
  • more perl: http://www.perlmonks.org/?node_id=660316
  • even more perl: https://metacpan.org/pod/Text::Balanced
  • perl, perl, perl: http://perl.plover.com/yak/regex/samples/slide083.html

And one more thing by Torsten Marek (who had pointed out correctly, that it's not a regex anymore):

  • http://coding.derkeiler.com/Archive/Perl/comp.lang.perl.misc/2008-03/msg01047.html