• 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"?

  • 相关阅读:
    JS跨域
    Cookie的Domain
    Mvc自定义分页控件
    SQLServer日期函数
    IIS里面网站停止了,不能启动
    JS面向对象
    我已下定决心,回郴州老家发展
    支持向量机
    无监督降维:主成分分析法
    机器学习概念--偏差方差、Pipeline及模型正则
  • 原文地址:https://www.cnblogs.com/buyishi/p/10385094.html
Copyright © 2020-2023  润新知