c++ 正则表达式使用 regex_search() 提取所有子字符串

标签 c++ regex

我是 C++ 正则表达式的新手。我有一个字符串“{1,2,3}”,我想提取数字 1 2 3。我想我应该使用 regex_search 但它失败了。

#include<iostream>
#include<regex>
#include<string>
using namespace std;
int main()
{
        string s1("{1,2,3}");
        string s2("{}");
        smatch sm;
        regex e(R"(\d+)");
        cout << s1 << endl;
        if (regex_search(s1,sm,e)){
                cout << "size: " << sm.size() << endl;
                for (int i = 0 ; i < sm.size(); ++i){
                        cout << "the " << i+1 << "th match" <<": "<< sm[i] <<  endl;
                }
        }
}

结果:

{1,2,3}
size: 1
the 1th match: 1

最佳答案

std::regex_search仅在找到第一个匹配项后返回。

什么std::smatch给你的是正则表达式中的所有匹配组。您的正则表达式只包含一组,所以 std::smatch里面只有一项。

如果您想查找所有匹配项,您需要使用 std::sregex_iterator .

int main()
{
    std::string s1("{1,2,3}");
    std::regex e(R"(\d+)");

    std::cout << s1 << std::endl;

    std::sregex_iterator iter(s1.begin(), s1.end(), e);
    std::sregex_iterator end;

    while(iter != end)
    {
        std::cout << "size: " << iter->size() << std::endl;

        for(unsigned i = 0; i < iter->size(); ++i)
        {
            std::cout << "the " << i + 1 << "th match" << ": " << (*iter)[i] << std::endl;
        }
        ++iter;
    }
}

输出:

{1,2,3}
size: 1
the 1th match: 1
size: 1
the 1th match: 2
size: 1
the 1th match: 3

end 迭代器是由设计默认构造的,因此当 iter 匹配项用完时,它等于 iter。请注意在循环的底部我执行 ++iter。这会将 iter 移动到下一个匹配项。当没有更多匹配时,iter 与默认构造的 end 具有相同的值。

另一个显示子匹配(捕获组)的示例:

int main()
{
    std::string s1("{1,2,3}{4,5,6}{7,8,9}");
    std::regex e(R"~((\d+),(\d+),(\d+))~");

    std::cout << s1 << std::endl;

    std::sregex_iterator iter(s1.begin(), s1.end(), e);
    std::sregex_iterator end;

    while(iter != end)
    {
        std::cout << "size: " << iter->size() << std::endl;

        std::cout << "expression match #" << 0 << ": " << (*iter)[0] << std::endl;
        for(unsigned i = 1; i < iter->size(); ++i)
        {
            std::cout << "capture submatch #" << i << ": " << (*iter)[i] << std::endl;
        }
        ++iter;
    }
}

输出:

{1,2,3}{4,5,6}{7,8,9}
size: 4
expression match #0: 1,2,3
capture submatch #1: 1
capture submatch #2: 2
capture submatch #3: 3
size: 4
expression match #0: 4,5,6
capture submatch #1: 4
capture submatch #2: 5
capture submatch #3: 6
size: 4
expression match #0: 7,8,9
capture submatch #1: 7
capture submatch #2: 8
capture submatch #3: 9

关于c++ 正则表达式使用 regex_search() 提取所有子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32553593/

相关文章:

c++ - 如何在不打开文件的情况下测试文件是否被锁定和/或只读?

c++ - Windows下的HDF5作为动态链接库Qt/C++

c++ - CMakeLists 不会包含 Boost header

javascript - 正则表达式,从字符串中选择第一个数字

r - 在 R 中处理日期正则表达式捕获组输出

c++ - 当没有更多引用时,如何从缓存中删除(非侵入式)智能指针?

c++ - 从 2D 网格上的点向外遍历的好算法是什么?

javascript - 需要有关 Javascript 正则表达式的帮助

javascript - 正则表达式或

regex - Oracle 11g 通过正则表达式获取所有匹配的事件