C++基礎-正則表達式 regex_match(匹配) regex_search(查找) regex_replace(替換)


正則匹配中的基礎符號

^開頭
()組
[]或,
{}幾次
$結尾

1.regex_match(匹配) 判斷當前的結構體是否符合正則匹配規則

#include<iostream>
#include<regex>

using namespace std;

//regex_match 匹配
//regex_search 查找
//regex_replace 替換


int main1()
{
    regex reg("([a-zA-Z]*) ([a-zA-Z]*)$");
    cmatch what; //匹配的詞語檢索出來
    bool isit = regex_match("id admin", what, reg); //
    for(int i = 0; i !=what.size(); ++i) //輸出匹配信息
    {
        cout << what[i+1].first << "\t";
    }
    cout << "match" << endl;
    if(isit)
    {

    }else
    {
        cout << "not match" << endl;
    }
    cin.get();
}

2.regex_search 判斷數字是否在目標結構體中

int main3()
{
    cmatch match;
    regex reg("\\d+"); //數字
    char str[50] = ("hello 8848 hello huahua180");
    bool isOk = regex_search(str, match, reg);
    std::cout << isOk << endl;
    if(isOk)
    {
        for(int i = 0; i != match.size(); i++)
        {
            cout << match[i].first << endl;
        }
    }
    cin.get();
}

3.regex_replace(替換)

將符合匹配條件的數字替換成其他的類型

int main()
{

    cmatch match;
    regex reg("\\d+"); //數字
    char str[50] = ("hello 8848, hello huahua180");
    cout << regex_replace(str, reg, "ABCDEFG") << endl;
    cin.get();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM