在 Linux 下使用 C++ 進行正則表達式編程,主要依賴于 <regex>
頭文件,該頭文件是在 C++11 標準中引入的。以下是一個簡單的示例,演示如何在 C++ 中使用正則表達式進行字符串匹配和提取。
#include <iostream>
#include <string>
#include <regex>
int main() {
// 要匹配的文本
std::string text = "我的郵箱是 example@example.com,聯系電話是 123-456-7890。";
// 定義正則表達式模式
// 1. 匹配郵箱地址
std::regex email_regex(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)");
// 2. 匹配電話號碼
std::regex phone_regex(R"(\d{3}-\d{3}-\d{4})");
// 用于存儲匹配結果
std::smatch matches;
// 匹配郵箱地址
if (std::regex_search(text, matches, email_regex)) {
std::cout << "找到郵箱: " << matches[0] << std::endl;
} else {
std::cout << "未找到郵箱。" << std::endl;
}
// 匹配電話號碼
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "找到電話號碼: " << matches[0] << std::endl;
} else {
std::cout << "未找到電話號碼。" << std::endl;
}
// 使用迭代器遍歷所有匹配項
std::string::const_iterator searchStart(text.cbegin());
while (std::regex_search(searchStart, text.cend(), matches, email_regex)) {
std::cout << "找到郵箱: " << matches[0] << std::endl;
searchStart = matches.suffix().first; // 更新搜索起始位置
}
return 0;
}
將上述代碼保存為 regex_example.cpp
,然后使用以下命令編譯:
g++ -std=c++11 -o regex_example regex_example.cpp
運行程序:
./regex_example
找到郵箱: example@example.com
找到電話號碼: 123-456-7890
找到郵箱: example@example.com
包含頭文件
#include <regex>
這是 C++ 標準庫中用于正則表達式的頭文件。
定義正則表達式
使用原始字符串字面量(R"(...)"
)可以避免轉義字符的麻煩。例如:
std::regex email_regex(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b)");
這個正則表達式用于匹配常見的郵箱格式。
匹配字符串
使用 std::regex_search
函數可以在字符串中搜索匹配正則表達式的子串:
if (std::regex_search(text, matches, email_regex)) {
std::cout << "找到郵箱: " << matches[0] << std::endl;
}
matches
是一個 std::smatch
對象,用于存儲匹配結果。matches[0]
包含整個匹配的子串。
遍歷所有匹配項
如果文本中可能包含多個匹配項,可以使用迭代器結合 std::regex_search
來逐一查找:
std::string::const_iterator searchStart(text.cbegin());
while (std::regex_search(searchStart, text.cend(), matches, email_regex)) {
std::cout << "找到郵箱: " << matches[0] << std::endl;
searchStart = matches.suffix().first; // 更新搜索起始位置
}
.
:匹配任意單個字符(除換行符外)*
:匹配前面的元素零次或多次+
:匹配前面的元素一次或多次?
:匹配前面的元素零次或一次{n}
:匹配前面的元素恰好 n 次{n,}
:匹配前面的元素至少 n 次{n,m}
:匹配前面的元素至少 n 次,最多 m 次[]
:定義字符集,如 [A-Za-z]
匹配任意字母()
:分組,用于捕獲匹配的子串|
:邏輯“或”,匹配多個模式之一C++ 版本:確保使用 C++11 或更高版本,因為 <regex>
是從 C++11 開始引入的。
編譯器支持:大多數現代編譯器(如 GCC、Clang、MSVC)都支持 C++11 及以上標準的正則表達式庫。
性能考慮:正則表達式的性能可能因模式的復雜性和輸入文本的大小而異。復雜的正則表達式可能導致性能問題,尤其是在大量文本處理時。
調試正則表達式:可以使用在線工具(如 regex101)來測試和調試正則表達式,以確保其按預期工作。
希望以上內容能幫助你在 Linux 下使用 C++ 進行正則表達式編程。如果有更多問題,歡迎繼續提問!