我正在使用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索引,那么格式化字符串的时间也会改变。
有没有一种干净利落的方法呢?就像命名组一样?如果有任何帮助,我将不胜感激。
发布于 2012-11-29 03:48:41
您可以使用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);发布于 2012-11-29 03:52:46
从名称/模式对动态构建regex_string,并返回名称->索引映射和正则表达式。然后编写一些代码来确定匹配是否来自给定的名称。
如果你疯了,你可以在编译时这样做(也就是从标签到索引的映射)。这不值得。
https://stackoverflow.com/questions/13612837
复制相似问题