正则表达式regex——C++11(十六)

<regex>

regex_match():与整个字符串进行匹配,匹配成功返回true.
regex_search(): 匹配的是子字符串,此外可能有子匹配(对应匹配中的子模式)
regex_replace(): 匹配并替换
regex_iterator: 迭代器,遍历一个字符序列,查找出匹配给定模式的所有子字符序列。

在任何重复符号(?,*,+及{})之后放一个?,会使匹配器查找最短匹配而非最长匹配。

void match()
{
    ifstream in("file.txt");
    if (!in)
        cerr << "no file"<<endl;
    regex pat{R"(^A*b+c?$)"};
    int lineno = 0;
    for (string line; getline(in, line);) {
        ++lineno;
        smatch matches; //匹配的字符串保存在这里
        if (regex_search(line, matches, pat)) {
            cout << lineno << ":" << matches[0] <<endl;
        }
    }
}
void test()
{
    string str = "am dd dbd& ++e*dd ddd";
    regex pat {R"(\s+(\w+))"};
    for (sregex_iterator p(str.begin(), str.end(), pat); p != sregex_iterator{}; ++p)
        cout << (*p)[1] << endl;
}
//sregex_iterator的含义就是regex_iterator<string>

猜你喜欢

转载自www.cnblogs.com/share-ideas/p/11965061.html
今日推荐