正則表示式庫 (C++11 起)
來自 cppreference.com
< cpp
正則表示式庫提供了一個表示正則表示式的類,正則表示式是一種用於在字串中執行模式匹配的微型語言。幾乎所有涉及正則表示式的操作都可以透過以下幾個物件來描述:
- 目標序列。用於搜尋模式的字元序列。這可以是由兩個迭代器指定的範圍、一個以空字元結尾的字串或一個 std::string。
- 模式。這即是正則表示式本身。它決定了什麼構成匹配。它是一個 std::basic_regex 型別的物件,由帶有特殊語法的字串構建。
- 匹配陣列。關於匹配的資訊可以作為 std::match_results 型別的物件檢索。
- 替換字串。這是一個字串,它決定了如何替換匹配項。
目錄 |
[編輯] 正則表示式語法
模式和替換字串支援以下正則表示式語法
- 修改的 ECMAScript 正則表示式語法。這是預設語法。
- 基本 POSIX 正則表示式語法.
- 擴充套件 POSIX 正則表示式語法.
- POSIX 中 awk 實用程式使用的正則表示式語法。
- POSIX 中 grep 實用程式使用的正則表示式語法。這實際上與基本 POSIX 正則表示式語法相同,但添加了換行符 '\n' 作為交替分隔符。
- POSIX 中 grep 實用程式在帶有 -E 選項時使用的正則表示式語法。這實際上與擴充套件 POSIX 正則表示式語法相同,但除了 '|' 之外,還添加了換行符 '\n' 作為交替分隔符。
某些語法變體(例如不區分大小寫的匹配)也可用,詳情請參見此頁面。
[編輯] 主要類
這些類封裝了正則表示式以及在目標字元序列中匹配正則表示式的結果。
(C++11) |
正則表示式物件 (類模板) |
(C++11) |
標識由子表示式匹配的字元序列 (類模板) |
(C++11) |
標識一個正則表示式匹配,包括所有子表示式匹配 (類模板) |
[編輯] 演算法
這些函式用於將封裝在正則表示式中的模式應用於目標字元序列。
(C++11) |
嘗試將正則表示式與整個字元序列匹配 (函式模板) |
(C++11) |
嘗試將正則表示式與字元序列的任何部分匹配 (函式模板) |
(C++11) |
用格式化的替換文字替換正則表示式的出現 (函式模板) |
[編輯] 迭代器
正則表示式迭代器用於遍歷序列中找到的所有正則表示式匹配項。
(C++11) |
迭代字元序列中所有正則表示式匹配項 (類模板) |
(C++11) |
迭代給定字串中所有正則表示式匹配中指定的子表示式或未匹配的子字串 (類模板) |
[編輯] 異常
此類定義了作為異常丟擲的物件型別,用於報告正則表示式庫中的錯誤。
(C++11) |
報告正則表示式庫生成的錯誤 (類) |
[編輯] 特性
正則表示式特性類用於封裝正則表示式的可本地化方面。
(C++11) |
提供正則表示式庫所需的字元型別元資訊 (類模板) |
[編輯] 常量
定義在名稱空間
std::regex_constants 中 | |
(C++11) |
控制正則表示式行為的通用選項 (typedef) |
(C++11) |
匹配特有的選項 (typedef) |
(C++11) |
描述不同型別的匹配錯誤 (typedef) |
[編輯] 示例
執行此程式碼
#include <iostream> #include <iterator> #include <regex> #include <string> int main() { std::string s = "Some people, when confronted with a problem, think " "\"I know, I'll use regular expressions.\" " "Now they have two problems."; std::regex self_regex("REGULAR EXPRESSIONS", std::regex_constants::ECMAScript | std::regex_constants::icase); if (std::regex_search(s, self_regex)) std::cout << "Text contains the phrase 'regular expressions'\n"; std::regex word_regex("(\\w+)"); auto words_begin = std::sregex_iterator(s.begin(), s.end(), word_regex); auto words_end = std::sregex_iterator(); std::cout << "Found " << std::distance(words_begin, words_end) << " words\n"; const int N = 6; std::cout << "Words longer than " << N << " characters:\n"; for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); if (match_str.size() > N) std::cout << " " << match_str << '\n'; } std::regex long_word_regex("(\\w{7,})"); std::string new_s = std::regex_replace(s, long_word_regex, "[$&]"); std::cout << new_s << '\n'; }
輸出
Text contains the phrase 'regular expressions' Found 20 words Words longer than 6 characters: confronted problem regular expressions problems Some people, when [confronted] with a [problem], think "I know, I'll use [regular] [expressions]." Now they have two [problems].