以下是一个C++代码示例,演示了如何使用正则表达式捕获所有匹配项并存储在一个向量中:
#include 
#include 
#include 
int main() {
    std::string text = "hello 123 world 456";
    std::regex regex("\\d+"); // 匹配所有的数字
    std::vector matches;
    std::sregex_iterator iterator(text.begin(), text.end(), regex);
    std::sregex_iterator endIterator;
    while (iterator != endIterator) {
        std::smatch match = *iterator;
        matches.push_back(match.str());
        iterator++;
    }
    // 输出所有匹配项
    for (const auto& match : matches) {
        std::cout << match << std::endl;
    }
    return 0;
}
    
此示例使用正则表达式\\d+来匹配所有的数字。它使用std::sregex_iterator类从字符串中找到所有匹配的项,并将它们存储在向量matches中。最后,它遍历向量并输出所有的匹配项。
下一篇:捕获所有堆分配