zoukankan      html  css  js  c++  java
  • C++正则表达式笔记

    C++11中引入了正则表达式库

    常用的3个接口:

    1.regex_match,完全匹配

    示例1:

    #include <iostream>
    #include <regex>
    int main()
    {
        std::string text = "long long ago";
        std::string text2 = "long long";
        std::regex re(".+ng");
        std::cout << std::boolalpha << std::regex_match(text, re) << std::endl;  //false
        std::cout << std::regex_match(text2, re) << std::endl;  //true
        std::system("pause");
        return 0;
    }

    示例1中匹配模式为.+ng,因为采用完全匹配,所以仅当目标文本以ng结尾才返回true

    2.regex_search,在目标文本中进行搜索

    示例2:

    #include <iostream>
    #include <regex>
    int main()
    {
        using namespace std;
        string text = "I'm 25.";
        string text2 = "I am 25 years old.";
        regex re("[0-9]+");
        smatch sm;
        if (regex_search(text, sm, re))
        {
            cout << sm[0] << endl;
        }
        if (regex_search(text2, sm, re))
        {
            cout << sm[0] << endl;
        }
        system("pause");
        return 0;
    }

    3.sregex_iterator,用于遍历所有匹配

    示例3:

    #include <iostream>
    #include <string>
    #include <regex>
    int main()
    {
        using namespace std;
        string text = "I'm 25. And my friend Bush is 24 years old.";
        regex re("[0-9]+");
        sregex_iterator itr1(text.begin(), text.end(), re);
        sregex_iterator itr2;
        for (sregex_iterator itr = itr1; itr != itr2; ++itr)
        {
            smatch sm = *itr;
            cout << sm[0].str() << endl;
        }
        system("pause");
        return 0;
    }

    P.S.

    目前没找到regex的标准发音,我将它读作“rej-eks”。参考链接:What is the correct way to pronounce "regex"?

  • 相关阅读:
    学习笔记:模拟退火
    我的 2020
    高一上文化课期末复习
    IOI 2020-2021 集训队作业
    学习笔记:插头DP
    NOIP2020 游记
    刷题记录
    学习笔记:四边形不等式优化 DP
    操作集合时 报错 java.lang.UnsupportedOperationException
    【编码】接收前端参数时,偶数汉字正常,奇数汉字乱码
  • 原文地址:https://www.cnblogs.com/buyishi/p/10385094.html
Copyright © 2011-2022 走看看