Boost logo

Boost Users :

Subject: Re: [Boost-users] [C++] Boost::Regex beginner question
From: Alan M. Carroll (amc_at_[hidden])
Date: 2008-12-18 18:59:01


Let's say you had an input form that was similar to that of Boost.Format except that you could specify type information by appending a '|' followed by the type, e.g. "%1|int%", and you could name the inserts as well as use numbers (e.g., "%count|int%"). After some preprocessing to pull out the types, you then wanted to strip the type specifiers to make the string Boost.Format compliant. So '%1|int%" would become "%1%" and "%2%" would remain unchanged (because type specifiers are not required).

// This matches the insert strings, e.g. "%1|int%" with subexpressions for the number or name
boost::regex const RXP_INSERT( "%(?:(\\d+)|([_a-z][_a-z0-9]*))(?:[|]([_a-z][_:a-z0-9]*))?%" , boost::regex_constants::icase);
// ...
// Time to strip the type specifiers. We match each insert then replace with the first two groups,
// exactly one of which will be set ($1 if a number, $2 if name)
            msgText = boost::regex_replace(msgText, RXP_INSERT,
"%$1$2%");
// No more type specifiers. Changing names to numbers is a bit more complex but this should illustrate
// the principle.

At 04:41 PM 12/18/2008, P.C. wrote:

my doubt is the following: I want to know how to do search and replace
regexp operations, like it can be done in Perl by using groups (expressions
surrounded by parentheses), which allow to select the substrings, matched by
the regexp, in the form of $1, $2

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net