|
Boost : |
From: Eric Niebler (eric_at_[hidden])
Date: 2008-03-16 03:22:10
Eric Niebler wrote:
> Robert Dailey wrote:
>> Perhaps in the future Boost.Xpressive can be extended to provide
>> this behavior. You could simply create a version of regex_replace()
>> that takes a functor as the replacement instead of a string.
>
> Nothing is simple. It would require careful design work, tests and
> docs.
I had some time today, so I looked into this. I noticed a few things:
1) Some time ago, I switched regex_match and regex_search to a
range-based interface (i.e., they traffic in ranges, basic_string is not
special), but never switched regex_replace.
2) There are open library issues against the std::regex_replace interface:
http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#726
http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#727
3) You are not the first person to want a regex_replace overload that
takes a formatter functor instead of a string:
http://lists.boost.org/boost-users/2006/05/19680.php
Long story short, I decided regex_replace was due for a major overhaul,
and match_results::format along with it. In the process, you got what
you wanted ... you can pass a functor instead of a format string.
The functor can have one of 3 signatures:
string (match_results)
OutIter (match_results, OutIter)
OutIter (match_results, OutIter, match_flag_type)
The formatter can be a function object, or even just a plain function.
So, for instance, you can do this:
map<string,string> replacements;
string my_format(smatch const &what)
{
return replacements[what[0].str()];
}
int main()
{
string input = ...;
sregex rx = ...;
string output = regex_replace(input, rx, my_format);
}
Old code that uses format strings still works as it did before. This is
committed to trunk and will not be part of the forthcoming 1.35 release.
None of this is documented yet -- it's experimental, and I reserve the
right to pull this at any time. :-) That said, I think it's a nice
extension, and I plan to keep it unless it causes problems.
-- 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