阅读量:0
在 Ubuntu 上使用 C++ 正则表达式库非常简单,因为这个库已经作为 C++ 标准库的一部分被包含进来。C++11 引入了 头文件,提供了对正则表达式的支持。下面是一个简单的例子,演示了如何在 Ubuntu 上使用 C++ 和正则表达式:
- 首先,确保你的编译器支持 C++11 或更高版本。在编译时,你需要添加
-std=c++11或-std=c++14或-std=c++17等选项来启用相应的标准。例如,使用 g++ 编译器:
g++ -std=c++11 your_file.cpp -o your_program
- 创建一个名为
your_file.cpp的 C++ 源文件,并在其中编写以下代码:
#include
#include
#include
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 << "Email found: " << matches[0] << std::endl;
} else {
std::cout << "Email not found." << std::endl;
}
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "Phone number found: " << matches[0] << std::endl;
} else {
std::cout << "Phone number not found." << std::endl;
}
return 0;
}
这个程序会在给定的文本中查找电子邮件地址和电话号码,并将它们打印出来。
- 使用 g++ 编译器编译你的程序:
g++ -std=c++11 your_file.cpp -o your_program
- 运行编译后的程序:
./your_program
你应该会看到以下输出:
Email found: example@example.com
Phone number found: 123-456-7890
这就是在 Ubuntu 上使用 C++ 正则表达式的基本方法。你可以根据需要修改正则表达式以匹配不同的模式。
以上就是关于“C++在Ubuntu上如何使用正则表达式”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm