📜  搭配| C++中的正则表达式(正则表达式)

📅  最后修改于: 2021-05-30 19:27:54             🧑  作者: Mango

smatch是match_results类模板的实例,用于字符串对象上的匹配。
可以使用smatch调用的函数:
可以调用match_results对象的str(),position()和length()成员函数来获取匹配的文本,或相对于主题字符串的匹配的起始位置及其长度。

  • 调用这些不带参数或以0为参数的成员函数以获取整体正则表达式匹配项。
  • 称他们通过1或更大,以获取特定捕获组的匹配项。
  • size()成员函数指示捕获组的数量,再加上一个用于整体匹配的组。
  • 因此,您可以将最大为size()-1的值传递给其他三个成员函数(str(),position(),length())。

什么是捕获组?
例子:

Example-1:
Suppose you create a regex object like : regex re("(geeks)(.*)") 
Here no of capturing group is = 2 
[ one is "geeks" and second is any character after "geeks" ].

Example-2:
regex re("a(b)c")
Here no of capturing group is = 1[ 'b' is the capturing group].
whatever within '(' and ')' braces is treated as capturing group.

下面是显示smatch的程序:

#include 
using namespace std;
int main()
{
    string sp("geeksforgeeks");
    regex re("(geeks)(.*)");
  
    // flag type for determining the matching behavior
    // && here it is for matches on strings.
    smatch match;
  
    // we can use member function on match
    // to extract the matched pattern.
    if (regex_search(sp, match, re) == true) {
  
        // The size() member function indicates the
        // number of capturing groups plus one for the overall match
        // match size = Number of capturing group + 1
        // (.*) which "forgeeks" ).
        cout << "Match size = " << match.size() << endl;
  
        // Capturing group is index from 0 to match_size -1 
        // .....here 0 to 2
        // pattern at index 0 is the overall match "geeksforgeeks"
        // pattern at index 1 is the first capturing group "geeks"
        // pattern at index 2 is the 2nd capturing group "forgeeks"
  
        cout << "Whole match : " << match.str(0) << endl;
        cout << "First capturing group is '" << match.str(1)
             << "' which is captured at index " << match.position(1)
             << endl;
        cout << "Second capturing group is '" << match.str(2)
             << "' which is captured at index " << match.position(2)
             << endl;
    }
    else {
        cout << "No match is found" << endl;
    }
    return 0;
}
输出:
Match size = 3
Whole match : geeksforgeeks
First capturing group is 'geeks' which is captured at index 0
Second capturing group is 'forgeeks' which is captured at index 5
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”