C 11 正規表示式

2021-08-16 22:02:55 字數 1989 閱讀 5491

1、驗證整個字串是否符合給定正規表示式

2、在字串中查詢符合給定正規表示式的子串

3、在字串中查詢符合正規表示式的子串,並替換

上述三點分別對應c++11中的三個函式,包含標頭檔案#include

使用函式std::regex_match(),一般都是分三步:

1、定義正規表示式 std::regex 類,將正規表示式的字串形式傳入其建構函式進行例項化;

2、定義std::smatch matchresult用來存放匹配結果,對應正規表示式中的括號,一般乙個括號為乙個子表示式,可以作為引數傳入函式第3步的函式,也可以不傳,省略;

3、呼叫std::regex_match()函式,匹配成功返回true。

呼叫std::regex_match()函式,匹配成功返回true。

//定義正規表示式,下面istr為string型別

std::regex reg("(\\d)\\.(\\d)\\.(\\d)\\.(\\d)");

std::smatch matchresult;//存放匹配成功時正規表示式中各個子表示式對應的實際字串,下標為0是整個正規表示式對應的字串

//以列舉形式過載的函式

if (std::regex_match((string::const_iterator)istr.begin(), (string::const_iterator)istr.end(), matchresult, reg))

//另乙個過載函式

if (std::regex_match(istr, matchresult, reg))

//regex_match()函式std::smatch型別引數可以省略,例如,但此引數在迴圈呼叫regex_search()函式時十分

if (std::regex_match(istr, reg))

使用函式std::regex_match(),一般都是分三步:

1、定義正規表示式 std::regex 類,將正規表示式的字串形式傳入其建構函式進行例項化;

2、定義std::smatch matchresult用來存放匹配結果,matchresult[0]對應整個正規表示式的匹配結果,matchresult[1]對應正規表示式的第乙個括號(第乙個子表示式)的匹配結果,以此類推;

3、呼叫std::regex_match()函式,匹配成功返回true。

步驟和上述類似,只不過第3步呼叫函式std::regex_search(),要返回所有符合正規表示式的子串,可以在while迴圈中實現:

std::regex reg("(\\d)\\.(\\d)\\.(\\d)\\.(\\d)");

string istr = "192.168.1.1";

std::smatch matchresult;

string::const_iterator iterator = istr.begin();

string::const_iterator iteratorend = istr.end();

while (std::regex_search(iterator, iteratorend, matchresult, reg))

注意,regex_replace()函式會替換所有符合給定正規表示式的子串,例如下例輸出結果為:"111111"

std::regex reg("[a-za-z]");

string istr = "abcdef";

//std::smatch matchresult;

string::const_iterator iterator = istr.begin();

string::const_iterator iteratorend = istr.end();

string result = std::regex_replace(istr, reg, "1");

cout << result;

詳細請參考:

C 11正規表示式

優勢 使得字串的處理更加簡單 一些相關的操作 驗證 檢查字串是否是想要的合法性 決策 判斷乙個輸入標書哪種字串 解析 從輸入的字串中查詢自己想要的資訊 轉換 搜尋字串,並將字串替換為新的格式化的字串 遍歷 搜尋字串所有出現的地方 符號化 根據一組分隔符將乙個字串分解為多個子字串 一些重要術語 模式 ...

c 11 正規表示式

include include 正規表示式標頭檔案 using namespace std regex search 檢索 regex replace 將檢索到的物件進行替換替換 match 是否匹配 void main cout 正規表示式實現字串的替換 void main 匹配時間 void m...

C 11 正規表示式

0.常用正規表示式 中文字元 u4e00 u9fa5 雙位元組字元 包括漢字在內 x00 xff 空白符 n s r 國內 號碼 d d d 18位身份證號 d d d d d 0 9 x 年 月 日 格式日期 0 9 1 9 0 9 1 9 0 9 0 9 1 9 0 9 1 9 0 9 0 13...