C++11 引入了標準正則表達式庫?<regex>
,它提供了強大且靈活的文本匹配和替換功能。下面為你詳細介紹該庫的相關內容,包括主要組件、使用方法、示例代碼等。
主要組件
std::regex
:用于表示一個正則表達式對象,可通過構造函數將字符串形式的正則表達式轉換為內部表示形式。std::smatch
:用于存儲字符串匹配的結果,包含了匹配的子字符串及其位置等信息。std::regex_match
:用于判斷整個輸入字符串是否與正則表達式匹配。std::regex_search
:用于在輸入字符串中查找與正則表達式匹配的子字符串。std::regex_replace
:用于將輸入字符串中與正則表達式匹配的部分替換為指定的字符串。
使用方法
1. 基本匹配
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "hello world";std::regex pattern("hello");if (std::regex_search(input, pattern)) {std::cout << "找到匹配項" << std::endl;} else {std::cout << "未找到匹配項" << std::endl;}return 0;
}
在上述代碼中,首先定義了一個輸入字符串?input
?和一個正則表達式對象?pattern
,然后使用?std::regex_search
?函數在?input
?中查找與?pattern
?匹配的子字符串。
2. 完整匹配
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "hello";std::regex pattern("hello");if (std::regex_match(input, pattern)) {std::cout << "完全匹配" << std::endl;} else {std::cout << "不完全匹配" << std::endl;}return 0;
}
這里使用?std::regex_match
?函數判斷?input
?是否與?pattern
?完全匹配。
3. 捕獲組
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "John Doe, 25";std::regex pattern("(\\w+) (\\w+), (\\d+)");std::smatch matches;if (std::regex_search(input, matches, pattern)) {std::cout << "姓名: " << matches[1] << " " << matches[2] << std::endl;std::cout << "年齡: " << matches[3] << std::endl;}return 0;
}
通過在正則表達式中使用括號?()
?定義捕獲組,std::smatch
?對象?matches
?可以存儲每個捕獲組匹配的結果,通過索引訪問這些結果。
4. 替換操作
#include <iostream>
#include <regex>
#include <string>int main() {std::string input = "Hello, World!";std::regex pattern("World");std::string replacement = "C++";std::string result = std::regex_replace(input, pattern, replacement);std::cout << "替換后的字符串: " << result << std::endl;return 0;
}
使用?std::regex_replace
?函數將?input
?中與?pattern
?匹配的部分替換為?replacement
。
注意事項
- 正則表達式語法:C++ 的正則表達式庫支持多種正則表達式語法,如 ECMAScript、basic、extended 等,默認使用 ECMAScript 語法。
- 性能問題:正則表達式匹配可能會帶來一定的性能開銷,特別是對于復雜的正則表達式和長字符串,使用時需要注意性能優化。
- 異常處理:在構造?
std::regex
?對象時,如果正則表達式語法錯誤,會拋?std::regex_error
?異常,需要進行適當的異常處理。
?