gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:02:22 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com