如何在表达式中迭代命名组

How to iterate named groups in xpressive?

本文关键字:迭代 表达式      更新时间:2023-10-16

假设我有一个sregex对象,像这样:

boost::xpressive::sregex::compile("(?P<firstword>\w+) (?<secondword>\w+)!");

我没能在表达式文档中找到任何关于这方面的参考,尽管表达式支持命名组很好。

我知道可以遍历组很好,但是我如何访问组名(如果组有名称的话)?

那么,我如何遍历命名组呢?

假设我们有你正在处理的整个正则表达式,在我看来,您似乎正在尝试创建一个匹配两个正则表达式的正则表达式命名捕获,因此尝试遍历命名捕获是无用的。

你只要试一下就可以了。

std::string str("foo bar");
sregex rx = sregex::compile("(?P<firstword>\w+) (?<secondword>\w+)!");
smatch what;
if(regex_search(str, what, rx))
{
    std::cout << "char = " << what["firstword"]  << what["secondword"] std::endl;
}

如果正则表达式是更复杂模式的一部分,为什么不使用静态命名的capture:http://www.boost.org/doc/libs/1_41_0/doc/html/xpressive/user_s_guide.html boost_xpressive.user_s_guide.named_captures.static_named_captures