Boost logo

Boost Users :

Subject: Re: [Boost-users] help using String Algorithms search and replace
From: Eric Niebler (eric_at_[hidden])
Date: 2010-10-28 19:46:09


On 10/28/2010 4:10 PM, John Dlugosz wrote:
> I need to (among other tasks) un-encode some substitutions in a string
> that use URL-encoding. That is, locate all occurrences of “%nn” and
> replace with the character whose ordinal is 0xnn.
>
> I looked at boost/algorithm/string.hpp, but the instructions are not at
> all clear. The tutorial/example is too simple, and the reference it
> points to for more info is quite unenlightening.
>
> Could someone show me how to do that, or point to an example that’s more
> along those lines?
>
> ===begin corporate footer===
<snip>
> The information transmitted
> is intended only for the person or entity to which it is addressed and
> may contain confidential and/or privileged material. Any review,
> retransmission, dissemination or other use of, or taking of any action
> in reliance upon, this information by persons or entities other than the
> intended recipient is prohibited.

I'm going to answer your question in spite of the potential dire legal
ramifications of doing so. PLEASE don't use sigs like this on this list.

Use Boost.Xpressive. It's the right tool for your job:

#include <stdlib.h>
#include <string>
#include <iostream>
#include <boost/xpressive/xpressive_static.hpp>
#include <boost/xpressive/regex_actions.hpp>
namespace xpr = boost::xpressive;

struct to_char_ : std::unary_function<xpr::ssub_match, std::string>
{
    std::string operator()(xpr::ssub_match const &s) const
    {
        char buf[] = {s.first[1], s.first[2], 0};
        return std::string(1, (char)(unsigned char)strtoul(buf, 0, 16));
    }
};

xpr::function<to_char_>::type const to_char = {};

int main()
{
    std::string data("This is %61 string with e%73cape sequences");
    xpr::sregex expr = '%' >> xpr::xdigit >> xpr::xdigit;
    std::cout << xpr::regex_replace(data, expr, to_char(xpr::s0))
              << std::endl;
}

This code prints:

This is a string with escape sequences

HTH,

-- 
Eric Niebler
BoostPro Computing
http://www.boostpro.com

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