在 CentOS 下使用 C++ 正则表达式,你需要使用 <regex>
头文件,它是 C++11 标准库的一部分。下面是一个简单的例子,展示了如何在 CentOS 下使用 C++ 正则表达式:
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string text = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
std::regex email_regex(R"((\w+@\w+\.\w+))");
std::regex phone_regex(R"((\d{3}-\d{3}-\d{4}))");
std::smatch matches;
// 查找电子邮件地址
if (std::regex_search(text, matches, email_regex)) {
std::cout << "Found email: " << matches[0] << std::endl;
} else {
std::cout << "Email not found." << std::endl;
}
// 查找电话号码
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "Found phone number: " << matches[0] << std::endl;
} else {
std::cout << "Phone number not found." << std::endl;
}
return 0;
}
要编译这个程序,请确保使用支持 C++11 的编译器(如 g++),并添加 -std=c++11
标志。例如:
g++ -std=c++11 main.cpp -o main
然后运行生成的可执行文件:
./main
这将输出:
Found email: example@example.com
Found phone number: 123-456-7890
请注意,这个例子使用了原始字符串字面量(R"(…)"),它允许你在正则表达式中直接使用反斜杠,而无需对其进行转义。这使得正则表达式更易于阅读和编写。