c++++ regex 庫提供了一種機制來處理正則表達式:創建 regex 對象來表示正則表達式模式。使用 regex_match 匹配整個字符串。使用 regex_search 匹配字符串中的第一個子串。使用 regex_replace 用替換字符串替換匹配的子串。
使用 C++ 函數庫進行正則表達式匹配
引言
正則表達式是一種強大且通用的模式匹配機制,可用于從文本中搜索和提取特定模式。C++ 標準函數庫提供了一組稱為 regular expressions(regex)庫的函數,可用于處理正則表達式。
regex 庫
regex 庫包含以下關鍵類和函數:
regex: 表示正則表達式模式。
regex_match: 匹配整個字符串。
regex_search: 匹配字符串中第一個子串。
regex_replace: 用替換字符串替換匹配的子串。
使用示例
下面是一個用 regex 庫匹配正則表達式的代碼示例:
#include <regex> #include <iostream> int main() { // 要匹配的字符串 std::string text = "abcdefghi"; // 匹配包含字母 "b" 的子串 std::regex re("[a-z]*b[a-z]*"); // 使用 regex_search 匹配 text std::smatch m; if (regex_search(text, m, re)) { std::cout << "匹配成功: " << m.str() << std::endl; } else { std::cout << "匹配失敗" << std::endl; } return 0; }
登錄后復制
實戰案例:驗證電子郵件地址
以下示例演示了如何使用 regex 庫來驗證電子郵件地址:
#include <regex> #include <iostream> int main() { // 電子郵件地址模式 std::regex re("^[\\w\\.-]+@([\\w\\-]+\\.)+[\\w\\-]+$"); // 用戶輸入的電子郵件地址 std::string email; std::cout << "請輸入電子郵件地址:"; std::cin >> email; // 使用 regex_match 驗證電子郵件地址 if (regex_match(email, re)) { std::cout << "電子郵件地址有效" << std::endl; } else { std::cout << "電子郵件地址無效" << std::endl; } return 0; }
登錄后復制