C++11新特性_标准库_正则表达式库

C++11 引入了标准正则表达式库 <regex>,它提供了强大且灵活的文本匹配和替换功能。下面为你详细介绍该库的相关内容,包括主要组件、使用方法、示例代码等。

主要组件

  • std::regex:用于表示一个正则表达式对象,可通过构造函数将字符串形式的正则表达式转换为内部表示形式。
  • std::smatch:用于存储字符串匹配的结果,包含了匹配的子字符串及其位置等信息。
  • std::regex_match:用于判断整个输入字符串是否与正则表达式匹配。
  • std::regex_search:用于在输入字符串中查找与正则表达式匹配的子字符串。
  • std::regex_replace:用于将输入字符串中与正则表达式匹配的部分替换为指定的字符串。

使用方法

  1. 基本匹配
cpp 复制代码
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string input = "hello world";
    std::regex pattern("hello");

    if (std::regex_search(input, pattern)) {
        std::cout << "找到匹配项" << std::endl;
    } else {
        std::cout << "未找到匹配项" << std::endl;
    }

    return 0;
}

在上述代码中,首先定义了一个输入字符串 input 和一个正则表达式对象 pattern,然后使用 std::regex_search 函数在 input 中查找与 pattern 匹配的子字符串。

  1. 完整匹配
cpp 复制代码
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string input = "hello";
    std::regex pattern("hello");

    if (std::regex_match(input, pattern)) {
        std::cout << "完全匹配" << std::endl;
    } else {
        std::cout << "不完全匹配" << std::endl;
    }

    return 0;
}

这里使用 std::regex_match 函数判断 input 是否与 pattern 完全匹配。

  1. 捕获组
cpp 复制代码
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string input = "John Doe, 25";
    std::regex pattern("(\\w+) (\\w+), (\\d+)");
    std::smatch matches;

    if (std::regex_search(input, matches, pattern)) {
        std::cout << "姓名: " << matches[1] << " " << matches[2] << std::endl;
        std::cout << "年龄: " << matches[3] << std::endl;
    }

    return 0;
}

通过在正则表达式中使用括号 () 定义捕获组,std::smatch 对象 matches 可以存储每个捕获组匹配的结果,通过索引访问这些结果。

  1. 替换操作
cpp 复制代码
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string input = "Hello, World!";
    std::regex pattern("World");
    std::string replacement = "C++";

    std::string result = std::regex_replace(input, pattern, replacement);
    std::cout << "替换后的字符串: " << result << std::endl;

    return 0;
}

使用 std::regex_replace 函数将 input 中与 pattern 匹配的部分替换为 replacement

注意事项

  • 正则表达式语法:C++ 的正则表达式库支持多种正则表达式语法,如 ECMAScript、basic、extended 等,默认使用 ECMAScript 语法。
  • 性能问题:正则表达式匹配可能会带来一定的性能开销,特别是对于复杂的正则表达式和长字符串,使用时需要注意性能优化。
  • 异常处理 :在构造 std::regex 对象时,如果正则表达式语法错误,会抛 std::regex_error 异常,需要进行适当的异常处理。
相关推荐
岁忧1 小时前
(LeetCode 面试经典 150 题) 200. 岛屿数量(深度优先搜索dfs || 广度优先搜索bfs)
java·c++·leetcode·面试·go·深度优先
一枝小雨1 小时前
【OJ】C++ vector类OJ题
数据结构·c++·算法·leetcode·oj题
一枝小雨1 小时前
【C++】Vector完全指南:动态数组高效使用
开发语言·c++·笔记·vector·学习笔记·std库
buyutang_1 小时前
C/C++ Linux系统编程:线程控制详解,从线程创建到线程终止
linux·c语言·c++·学习
Qiang_san2 小时前
GNU Make | C/C++项目自动构建入门
c语言·c++·gnu
源代码•宸2 小时前
Leetcode—2749. 得到整数零需要执行的最少操作数【中等】(__builtin_popcountl)
c++·经验分享·算法·leetcode·位运算
芒果敲代码3 小时前
单一职责原则(SRP)
c++·单一职责原则
ComputerInBook3 小时前
C++编程语言:标准库:第37章——正则表达式(Bjarne Stroustrup)
开发语言·c++·正则表达式
青草地溪水旁3 小时前
C/C++中的可变参数 (Variadic Arguments)函数机制
c语言·c++·可变参数
汉克老师4 小时前
第十四届蓝桥杯青少组C++选拔赛[2023.2.12]第二部分编程题(1、求和)
c++·蓝桥杯·蓝桥杯c++·c++蓝桥杯