c ++ regex使用regex_search()

时间:2015-09-13 19:17:42

标签: 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

1 个答案:

答案 0 :(得分:12)

仅在找到第一个匹配后

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