📌  相关文章
📜  查找字符串中正则表达式的所有匹配项的程序

📅  最后修改于: 2021-04-26 18:24:28             🧑  作者: Mango

先决条件:匹配| C++中的正则表达式(正则表达式)

给定一个正则表达式,任务是在字符串查找所有正则表达式匹配项。

  • 不使用迭代器:
    // C++ program to find all the matches
    #include 
    using namespace std;
    int main()
    {
        string subject("My GeeksforGeeks is my " 
                        "GeeksforGeeks none of your GeeksforGeeks");
      
        // Template instantiations for
        // extracting the matching pattern.
        smatch match;
        regex r("GeeksforGeeks");
        int i = 1;
        while (regex_search(subject, match, r)) {
            cout << "\nMatched string is " << match.str(0) << endl
                 << "and it is found at position " 
                 << match.position(0)<
    输出:
    Matched string is GeeksforGeeks
    and it is found at position 3
    
    Matched string is GeeksforGeeks
    and it is found at position 7
    
    Matched string is GeeksforGeeks
    and it is found at position 14
    

    注意:上面的代码运行得很好,但是问题是输入字符串将丢失。

  • 使用迭代器:
    对象可以通过调用具有三个参数的构造来构建:将字符串迭代指示搜索的开始位置,一个字符串迭代指示搜索的结束位置,和该正则表达式的对象。使用默认构造函数构造另一个迭代器对象,以获取序列结束迭代器。
    #include 
    using namespace std;
    int main()
    {
        string subject("geeksforgeeksabcdefghg"
                       "eeksforgeeksabcdgeeksforgeeks");
      
        // regex object.
        regex re("geeks(for)geeks");
      
        // finding all the match.
        for (sregex_iterator it = sregex_iterator(subject.begin(), subject.end(), re);
             it != sregex_iterator(); it++) {
            smatch match;
            match = *it;
            cout << "\nMatched  string is = " << match.str(0)
                 << "\nand it is found at position "
                 << match.position(0) << endl;
            cout << "Capture " << match.str(1)
                 << " at position " << match.position(1) << endl;
        }
        return 0;
    }
    
    输出:
    Matched  string is = geeksforgeeks
    and it is found at position 0
    Capture for at position 5
    
    Matched  string is = geeksforgeeks
    and it is found at position 21
    Capture for at position 26
    
    Matched  string is = geeksforgeeks
    and it is found at position 38
    Capture for at position 43