I'm using boost::regex to parse some formatting string where '%' symbol is escape character. Because I do not have much experience with boost::regex, and with regex at all to be honest I do some trial and error. This code is some kind of prototype that I came up with.

std::string regex_string = 
            "(?:%d\\{(.*)\\})|"                   //this group will catch string for formatting time
            "(?:%([hHmMsSqQtTlLcCxXmMnNpP]))|"    //symbols that have some meaning
            "(?:\\{(.*?)\\})|"                    //some other groups
            "(?:%(.*?)\\s)|"
            "(?:([^%]*))";

    boost::regex regex;
    boost::smatch match;

    try
    {
        regex.assign(regex_string, boost::regex_constants::icase);
        boost::sregex_iterator res(pattern.begin(), pattern.end(), regex);
        //pattern in line above is string which I'm parsing
        boost::sregex_iterator end;
        for(; res != end; ++res)
        {
            match = *res;
            output << match.get_last_closed_paren();
            //I want to know if the thing that was just written to output is from group describing time string
            output << "\n";
        }


    }
    catch(boost::regex_error &e)
    {
        output<<"regex error\n";
    }

And this works pretty good, on the output I have exactly what I want to catch. But I do not know from which group it is. I could do something like match[index_of_time_group]!="" but this is kind of fragile, and doesn't look too good. If I change regex_string index that was pointing on group catching string for formatting time could also change.

Is there a neat way to do this? Something like naming groups? I'll be grateful for any help.

有帮助吗?

解决方案

You can use boost::sub_match::matched bool member:

if(match[index_of_time_group].matched) process_it(match);

It is also possible to use named groups in regexp like: (?<name_of_group>.*), and with this above line could be changed to:

if(match["name_of_group"].matched) process_it(match);

其他提示

Dynamically build regex_string from pairs of name/pattern, and return a name->index mapping as well as the regex. Then write some code that determines if the match comes from a given name.

If you are insane, you can do it at compile time (the mapping from tag to index that is). It isn't worth it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top