1

我正在使用 boost::regex 解析一些格式字符串,其中 '%' 符号是转义字符。因为我在 boost::regex 方面没有太多经验,而且说实话,我对 regex 进行了一些试验和错误。这段代码是我想出的某种原型。

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";
    }

这很好用,在输出上我有我想要捕捉的东西。但我不知道它来自哪个组。我可以做类似match[index_of_time_group]!=""的事情,但这有点脆弱,看起来不太好。如果我更改regex_string指向组捕获字符串以格式化时间的索引也可能会更改。

有没有一种巧妙的方法来做到这一点?诸如命名组之类的东西?我将不胜感激任何帮助。

4

2 回答 2

1

您可以使用boost::sub_match::matchedbool 成员:

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

也可以在正则表达式中使用命名组,例如:(?<name_of_group>.*),并且上面的行可以更改为:

if(match["name_of_group"].matched) process_it(match);
于 2012-11-28T19:48:41.013 回答
0

从名称/模式对动态构建regex_string,并返回名称->索引映射以及正则表达式。然后编写一些代码来确定匹配是否来自给定的名称。

如果你疯了,你可以在编译时做(从标签到索引的映射)。这不值得。

于 2012-11-28T19:52:46.157 回答