tags:

views:

76

answers:

1

I'm no expert on Regex. I'm trying to create a regular expression that will match the exact same number of opening and closing braces, but I'm stumped on how to do it.

An example:

nothing: important, a b { c {{{ a another {{ nothing }} }}} }

or:

one { two {{ error, forgot ending brace }}

The problem is that I don't know how many braces I'm going to get beforehand. In the first example, I need to get the text { c {{{ a another {{ nothing }} }}} }. In the second I need to get {{ error, forgot ending brace }}.

Is it even possible to create a matching rule that will do this? (I'm using Qt Regex engine).

+5  A: 

This problem cannot be solved using regular grammar => it cannot be done by regular expression.

Messa
I think it can be solved with REGEX pretty easily, with repeatedly matching the output of the expression "{(*.)}", but that's worse than using simple string function.
Dor
True, such a language is not regular. However, certain regex engines have extended functionality, e.g. the .NET one, which is capable of matching brackets using so called "balanced group definitions": http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx. QT unfortunately doesn't support that (http://doc.trolltech.com/4.6/qregexp.html, "Note that in general regexps cannot be used to check for balanced brackets or tags. However, it is possible to write a regexp that will match nested brackets or tags correctly, but only if the number of nesting levels is fixed and known. If the number of
0xA3