如何检查使用哪个匹配组进行匹配(boost-regex)
How to check which matching group was used to match (boost-regex)
我正在使用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
,并返回名称>索引映射以及正则表达式。 然后编写一些代码来确定匹配是否来自给定名称。
如果你疯了,你可以在编译时这样做(从标签到索引的映射)。 不值得。
相关文章:
- boost::any 如何检查空值/未定义的值
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 在VC2015U3上,std::regex比boost::regex慢得多
- 使用 boost::regex (c++) 比较两个正则表达式
- Build Boost Regex for Windows VS2013
- boost::regex 和std::regex之间的不一致?
- 尝试使用生成文件编译程序时"fatal error: boost/regex.hpp: No such file or directory" C++
- boost :: asio :: io_service检查是否为null
- 带有Boost Regex库的未解决的外部对象
- boost::regex链接问题在Xcode 4.5.2中
- 如何检查使用哪个匹配组进行匹配(boost-regex)
- boost::regex和std::regex之间的不一致
- Boost.Regex parsing
- BOOST.REGEX定界器解析
- 以下等级表达式不适合Boost Regex
- 在Windows C 代码:: Blocks上的Boost Regex
- Boost Regex用于格式化MAC地址字符串
- 使用 c++/boost::regex 提取 HTML 文件的特定部分
- 使用 boost::regex 更改文件中数据的格式
- 在OS X上使用clang编译boost regex时发生链接错误