Boost logo

Boost :

From: Eric Niebler (eric_at_[hidden])
Date: 2007-05-01 12:02:48


John Maddock wrote:
> Lorenzo Bettini wrote:
>> do you happen to know whether there are any specifications for regular
>> expressions for matching parenthesis (I mean in any regexp frameworks
>> or libraries)?
>
> Not really no, but I have another idea, assuming the x-modifier is on:
>
> (?x)
> (?:
> (\()
> |(\[)
> |(\{)
> )
> foo
> (?:
> (?(1)\)
> |(?:(?(2)\]
> |(?:\}
> ))))
>
> The idea is to use conditional expressions to check which opening backet
> matched and then react accordingly. You'll need to check I've got the ('s
> and )'s matching up 'cos I lost count while typing in :-(

You can do something similar with xpressive (alternate regex engine
which will be in boost 1.34):

     cregex rx = cregex::compile(
         "(\\(()|\\[()|\\{())foo(\\4\\}|\\3\\]|\\2\\))");

     if(regex_match("(foo)", rx))
     {
         std::cout << "match!\n";
     }
     if(!regex_match("(foo]", rx))
     {
         std::cout << "no match!\n";
     }

For each alternate, you create an empty capture with "()". Then you
match that capture again in the balanced alternate on the other side.
Backreferences (even empty ones) only match if their capture
participated in the match.

As a static regex, this would look like:

cregex rx =
    ('(' >> (s1=nil) | '[' >> (s2=nil) | '{' >> (s3=nil))
>> "foo"
    (s3 >> '}' | s2 >> ']' | s1 >> ')')

This avoids the need to double-escape everything.

-- 
Eric Niebler
Boost Consulting
www.boost-consulting.com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk