【问题标题】:Boost Regular Expression: Getting the Named GroupBoost 正则表达式:获取命名组
【发布时间】:2015-12-20 16:27:50
【问题描述】:

如何使用 Boost 正则表达式获取模式匹配对应的组名?

下面会将匹配的表达式输出到给定的模式。但是如何获取对应的命名组呢?

boost::regex pattern("(?<alpha>[0-9]*\\.?[0-9]+)|(?<beta>[a-zA-Z_]+)");

string s = "67.2 x  7 I am";

string::const_iterator start = s.begin();
string::const_iterator end   = s.end();
boost::sregex_token_iterator i(start, end, pattern);
boost::sregex_token_iterator j;

for ( ;i != j; ++i)
{
    cout << *i << endl;
        // '67.2' and '7' belongs to "alpha"
        // 'x', 'I', 'am' belongs to "beta"
}

【问题讨论】:

    标签: c++ regex boost


    【解决方案1】:

    You can get it from match_result 它适用于 xpressive,但同样适用于 Boost.Regex

    【讨论】:

    • 为什么要链接到不同库的文档?
    • @sehe 1) 我把两者都链接了。 2) 我不太确定 OP 实际使用的是什么。
    • 2) boost::regex - 我敢肯定这是非常确定的
    • @sln 奇怪,我链接的 Boost.regex 的文档说“接受字符串的重载,返回对 sub_match 对象的引用,该对象表示与命名的子表达式 n 匹配的字符序列。”
    • @RevolverOcelot - 确实,你是对的。我刚刚用boost::regex 试过这个,match["name"].str() 确实有效。我想很久以前我希望得到 name 给定一个组 number 和签证/反之亦然。非常感谢。这就是我在 SO 阅读琐事的原因。顺便说一句,知道如何在替换端的regex_replace() 中使用 named 组(而不是通过回调)。我只是在谈论常规的正则表达式,而不是富有表现力的。谢谢! +1
    猜你喜欢
    • 2019-03-17
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多