如何检查使用哪个匹配组进行匹配(boost-regex)

How to check which matching group was used to match (boost-regex)

本文关键字:boost-regex 何检查 检查      更新时间:2023-10-16

我正在使用boost::regex来解析一些格式字符串,其中"%"符号是转义字符。因为我对 boost::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 errorn";
    }

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

有没有一种巧妙的方法可以做到这一点?像命名组一样?我将不胜感激任何帮助。

您可以使用boost::sub_match::matched布尔成员:

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

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

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

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

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