Boost logo

Boost :

From: Dave Jenkins (david_at_[hidden])
Date: 2008-03-14 23:18:47


> Thank you very much for helping. I wouldn't go as far as to say it isn't
> hard, because that looks very hard IMHO. I was hoping for something a
> little
> more intuitive and built-in.

You could also use Xpressive static regular expressions with semantic
actions to get a really simple solution. At least I think it's simple;
hopefully you will too. :-)

The example program below uses a function object to lookup the variable
names and return replacement strings that are copied to the output string.
Of course you can replace my "if" statement with your localization table.
All normal text characters are simply copied to the output string.

Also, if you have a lot of variable names to lookup, try using Xpressive
symbol tables. They're really fast!
HTH,
Dave Jenkins

#include <string>
#include <iostream>
#include <boost/xpressive/xpressive.hpp>
#include <boost/xpressive/regex_actions.hpp>

namespace xp = boost::xpressive;

// function object to lookup a variable name and return a replacement string
struct lookup_impl {
    typedef std::string result_type;
    result_type operator() (std::string const& s1) const
    {
        if (s1 == "variable1")
            return "V1";
        else if (s1 == "var2")
            return "V2";
        return "V3";
    }
};
// lazy function for lookup
xp::function<lookup_impl>::type const lookup = {{}};

int main()
{
    using namespace boost::xpressive;

    std::string input("This string $(variable1) has localized $(var2) text
interleaved for no $(reason)");
    std::string output;

    // match normal characters, i.e., not '$'
    sregex rx_text = (*(~set['$']))
        [ xp::ref(output) += _ ]; // copy the characters to output

    // match variable names, e.g., $(name)
    sregex rx_variable = "$(" // match prefix
>> (s1 = +(~set[')'])) // match variable name
            // lookup the variable name replacement and copy it to output
            [ xp::ref(output) += lookup(_) ]
>> ")"; // match suffix

    // match normal characters interleaved with variable names
    sregex rx = rx_text >> *(rx_variable >> rx_text);

    regex_match(input, rx);
    // this outputs "This string V1 has localized V2 text interleaved for no
V3"
    std::cout << output << '\n';
    return 0;
}


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