商城首页欢迎来到中国正版软件门户

您的位置: 首页 > 文章列表 > 编程开发 > C++ Linux系统中如何使用正则表达式

C++ Linux系统中如何使用正则表达式

  发布于2026-07-18 阅读(0)

扫一扫,手机访问

在C++里处理正则表达式,最直接的方式就是借助库。这个库从C++11开始正式加入标准,所以只要你的编译器支持C++11及以上版本,就能直接上手。下面用一个实际例子演示在Linux环境下如何用C++正则表达式做匹配。

C++ Linux系统中如何使用正则表达式

先看代码:

#include 
#include 
#include 

int main() {
    // 要匹配的正则表达式
    std::string pattern = R"(\d+)"; // 匹配一个或多个数字
    // 要搜索的文本
    std::string text = "Hello, there are 123 apples and 456 oranges.";

    // 创建一个正则表达式对象
    std::regex regex(pattern);

    // 使用std::sregex_iterator来遍历所有匹配项
    auto words_begin = std::sregex_iterator(text.begin(), text.end(), regex);
    auto words_end = std::sregex_iterator();

    std::cout << "Found " << std::distance(words_begin, words_end) << " numbers in the text." << std::endl;

    for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
        std::smatch match = *i;
        std::string match_str = match.str();
        std::cout << "Found number: " << match_str << std::endl;
    }

    return 0;
}

编译时记得打开C++11标准:

g++ -std=c++11 your_file_name.cpp -o your_output_file_name

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

./your_output_file_name

程序会在文本中找出所有匹配正则表达式的子串并打印出来。拿这个例子来说,它会在“Hello, there are 123 apples and 456 oranges.”里找到两个数字:123和456,然后逐一输出。整个过程清晰直观,适合作为正则表达式入门的起点。

本文转载于:https://www.yisu.com/ask/11953124.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注