c++ - 如何获取未知数量的正则表达式匹配项?

标签 c++ regex c++14

我试图在字符串中找到几个数字位置。我只能获取最后一位或之前指定的位数:

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string s("aaabbbccd123456eeffgg");
    std::smatch match;
    std::regex braced_regex("(\\w+)(\\d{2,})(\\w+)");
    std::regex plus_regex("(\\w+)(\\d+)(\\w+)");

    auto printer = [](auto& match) {
            std::ssub_match sub(match);
            std::string match_substring(sub.str());
            std::cout <<  match_substring << '\n';
    };

    std::regex_match(s, match, braced_regex);
    std::cout << "Number of braced matches: " << match.size() << '\n';  
    std::for_each(match.begin(), match.end(), printer);

    std::regex_match(s, match, plus_regex);
    std::cout << "Number of plus matches: " << match.size() << '\n';  
    std::for_each(match.begin(), match.end(), printer);
    return 0;
}

结果:

Number of braced matches: 4
aaabbbccd123456eeffgg
aaabbbccd1234
56
eeffgg
Number of plus matches: 4
aaabbbccd123456eeffgg
aaabbbccd12345
6
eeffgg

如何从提供的字符串中获取整个数字序列,即 123456?

最佳答案

([a-zA-Z]+)(\\d{2,})([a-zA-Z]+)

你可以试试这个。\w===[a-zA-Z0-9_]。所以\w+将匹配max它可以。所以它让 \d{2,} 只有 2。

(\\w+?)(\\d{2,})(\\w+)

使第一个 \w 不贪婪。请参阅live demo .

关于c++ - 如何获取未知数量的正则表达式匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27419136/

相关文章:

c++ - 未调用析构函数时销毁类成员

c++ - 将节点添加到链表的前面,然后计算链表中的节点数

regex - 使用 "OR"条件的正则表达式

正则表达式测试字符串是否以 http ://or https://开头

c++ - 嵌套 ifs 与串行逻辑 block

python - 不可能的反向引用

c++ - 将函数应用于元组的每个元素

c++ - C++ 中对 const Callable 的引用和对 Callable 的引用之间的区别

c++ - 带有条件语句错误的constexpr,使用Stroustrup示例

c++ - 按类型获取元组元素(C++0x 之前)