C++正则表达式regex_match,regex_search和regex_replace简单使用

时间:2024-05-18 16:53:01

一、说明:
C++11之后引入了正则表达式,给文本处理带来了很多方便的地方,正则表达式处理能力很强但想熟练使用并不容易,C++中主要使用下面的三个函数进行正则表达的操作。
1、regex_search:在整个字符串中匹配到符合正则表达式规则中的一部分就返回true,也就是子串。
2、regex_match:在整个字符串中匹配到符合整个表达式的整个字符串时返回true,也就是匹配的是整个字符串。
3、regex_replace:在整个字符串中替换符合正则表达式规则的字段。

二、测试代码:

#include <iostream>
#include <regex>
#include <string>
#include <iterator>

using namespace std;

int main()
{
    system("COLOR 1F");

    cout << "==========regex_search=========" << endl;
    string srcStr("---ISMILE--2019-01-24--ISMILE-THURSDAY");
    std::smatch m;
    std::regex e("\\d{4}-\\d{2}-\\d{2}");
    if(std::regex_search(srcStr,m,e,regex_constants::match_default))
    {
        for(auto iter : m)
        {
            cout << iter << endl;
        }
        string tempStr = m.suffix().str();
        cout << "tempStr:" <<tempStr << endl;
        string mbeginStr = *m.begin();
        cout << "mbeginStr:" << mbeginStr << endl;
        string mEndStr = *(m.end()-1);
        cout << "mEndStr:" << mEndStr << endl;
        int length = m.size();
        cout << "length:" << length << endl;
        cout << "m.prefix():"<< m.prefix().str() << endl;
    }

    cout << "========regex_match=======" << endl;
    const char *strch = srcStr.c_str();
    std::cmatch cm;
    std::regex ce("(.*)(ISMILE)(.*)");
    if(std::regex_match(strch,cm,ce,regex_constants::match_default))
    {
        cout << "cm.size=" << cm.size() << endl;
        for(auto iter:cm)
        {
            cout <<iter<<endl;
        }
    }

    cout << "========regex_replace=======" << endl;
    string tmpStr("this is ISMILELI's test for regex!");
    std::regex eStr("(ISMILE)");
    std::string result;
// 此处改成$2时结果打印是"this is LI's test for regex!",可以参考测试代码中的result3的打印结果多方寻找答案不得,这个地方的参数传值[官方的描述](http://www.cplusplus.com/reference/regex/regex_replace/)是大于0的不超
//过两位数的整数
    std::regex_replace(std::back_inserter(result),tmpStr.begin(),tmpStr.end(),eStr,"$1");
    cout << "result:" << result << endl;

    string tmpStr2("ISMILE,ISMILELI,SMILE");
    std:regex eStr2("(ISMILE)");
    std::string result2;
    std::regex_replace(std::back_inserter(result2),tmpStr2.begin(),tmpStr2.end(),eStr2,"lisa-$1");
    cout << "result2:" << result2 << endl;
    std::string result3;
    std::regex_replace(std::back_inserter(result3),tmpStr2.begin(),tmpStr2.end(),eStr2,"lisa$2");
    cout << "result3:" << result3 << endl;
    return 0;
}

三、运行结果:

C++正则表达式regex_match,regex_search和regex_replace简单使用