
在 Linux 系统下,C++ 程序可借助 <regex></regex> 库高效处理正则表达式。该库是 C++11 的标准组件,请确保您的编译器支持 C++11 或更高版本。
以下代码示例演示了如何在 C++ 中应用正则表达式:
<code class="c++">#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "我的邮箱是 example@example.com,电话号码是 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 << "邮箱地址: " << matches[1] << std::endl;
}
// 查找电话号码
if (std::regex_search(text, matches, phone_regex)) {
std::cout << "电话号码: " << matches[1] << std::endl;
}
return 0;
}</code>编译该代码,请使用 -std=c++11 或更高版本标准编译选项:
<code class="bash">g++ -std=c++11 main.cpp -o main</code>
运行编译后的可执行文件:
立即学习“C++免费学习笔记(深入)”;
<code class="bash">./main</code>
程序输出结果将显示找到的邮箱地址和电话号码。
本例中,我们使用了两个正则表达式分别匹配邮箱地址和电话号码。std::regex_search 函数用于在文本字符串中查找匹配的子字符串。如果找到匹配项,则匹配结果将存储在 std::smatch 对象中,方便我们提取匹配文本。
以上就是C++在Linux中如何使用正则表达式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号