C 11 正規表示式 例項3

2022-07-03 20:12:10 字數 1622 閱讀 6433

下面乙個例子將進行年月日格式的轉換,將dd-mm-yyyy –> yyyy-mm-dd,其中『.』或者『/』都能正確識別。

#include

#include

#include

std::string format_date(const std::string& date)

)(\\.|-|/)(\\d)(\\.|-|/)(\\d)");

// transformation pattern, reverses the position of all capture groups

std::string replacer = "$5$4$3$2$1";

return std:: regex_replace(date, pattern, replacer);

}int main()

執行結果:

說明,這個例子也很有實用價值,這裡用到的正規表示式的匹配模式前面都已經進行過說明就不在分析。

相信通過以上例子,對正規表示式的運用已經有了乙個不錯的了解,下面再來新增乙個例項,加深一下理解。

下面乙個例子用來查詢給定文字中new的個數和delete的個數是否相等:

#include

#include

#include

int main()

if (new_counter!=delete_counter)

std::cout << "leak detected!\n";

else

std::cout << "seems ok...\n";

std::cout << std::endl;

}執行結果:

執行結果表明,new和delete的數量不相等,也就是發生了「記憶體洩露」。

為了幫助理解,上面對於match_results型別的下標操作的意義,請看isoiec14882 c++11的說明:

執行結果:

執行結果:

C 11 正規表示式 例項2

下面來介紹和regex match 很像的regex search 的使用例項,regex match 要求正規表示式必須與模式串完全匹配,regex search 只要求存在匹配項就可以。include include include int main std cout 執行結果 上面這個例子只能...

C 11 正規表示式 例項2

下面來介紹和regex match 很像的regex search 的使用例項,regex match 要求正規表示式必須與模式串完全匹配,regex search 只要求存在匹配項就可以。include include include int main std cout 執行結果 上面這個例子只能...

C 11正規表示式

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