c++ - 如何检查哪个匹配组被用来匹配(boost-regex)

标签 c++ regex parsing c++11 boost-regex

我正在使用 boost::regex 来解析一些格式化字符串,其中“%”符号是转义字符。因为我对 boost::regex 没有太多经验,老实说,我对 regex 完全没有经验,所以我做了一些试验和错误。这段代码是我想出的某种原型(prototype)。

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 索引也可能会更改。

有没有一个巧妙的方法来做到这一点?命名组之类的东西?我将不胜感激。

最佳答案

您可以使用 boost::sub_match::matched bool 成员:

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

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

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

关于c++ - 如何检查哪个匹配组被用来匹配(boost-regex),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13612837/

相关文章:

java - Apache Marmotta LDPath 库 - 选择 URI fn :content

c++ - 如何用C++创建一个高效的可移植定时器?

c++ - Python PIL Image.tostring ('raw' ) 和 OpenCV 的 IplImage->imageData

c++ - 内存泄漏如何提高性能

java - 搜索字符串中的单引号并将其与其他字符括起来

php - 用单个空格替换制表符和空格,用单个换行符替换回车和换行符

c++ - Boost Asio - 消息内容传输错误

javascript - 如何使用 JavaScript 返回字符串中每个链接的长度?

c语言: read file content as numbers and add them together

c# - C# 中需要 xmlElement 解析器