Ubuntu下C++如何使用正则表达式

905
2025/3/5 6:32:16
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Ubuntu 下,C++ 可以通过 <regex> 库来使用正则表达式。这是一个 C++11 标准库的一部分,所以你需要确保你的编译器支持 C++11 或更高版本。

下面是一个简单的示例,演示了如何在 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 << "Email found: " << matches[0] << std::endl;
    } else {
        std::cout << "No email found." << std::endl;
    }

    // 查找电话号码
    if (std::regex_search(text, matches, phone_regex)) {
        std::cout << "Phone number found: " << matches[0] << std::endl;
    } else {
        std::cout << "No phone number found." << std::endl;
    }

    return 0;
}

要编译此代码,请确保使用 -std=c++11 或更高版本的标志。例如,使用 g++ 编译器:

g++ -std=c++11 main.cpp -o main

然后运行生成的可执行文件:

./main

这将输出:

Email found: example@example.com
Phone number found: 123-456-7890

在这个示例中,我们使用了两个正则表达式:一个用于匹配电子邮件地址,另一个用于匹配电话号码。std::regex_search 函数用于在文本中查找与正则表达式匹配的子串。如果找到匹配项,它将返回 true,并将匹配项存储在 std::smatch 对象中。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: ubuntu远程连接命令是什么