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 异常,需要进行适当的异常处理。
相关推荐
木子.李34730 分钟前
数据结构-算法学习C++(入门)
数据库·c++·学习·算法
半青年2 小时前
IEC61850规约客户端软件开发实战(第二章)
java·c++·qt·网络协议·c#·信息与通信·iec61850
moz与京2 小时前
【数据结构】字符串操作整理(C++)
开发语言·数据结构·c++
linff9113 小时前
Reactor和Proactor
c++·网络编程’
末日汐4 小时前
STL-list
开发语言·c++
qq_433554544 小时前
C++ list数据删除、list数据访问、list反转链表、list数据排序
开发语言·c++·list
uyeonashi4 小时前
【从零开始学习QT】快捷键、帮助文档、Qt窗口坐标体系
开发语言·c++·qt·学习
愚润求学5 小时前
【Linux】mmap文件内存映射
linux·运维·服务器·开发语言·c++
乌鸦9446 小时前
《STL--stack 和 queue 的使用及其底层实现》
开发语言·c++·priority_queue·适配器stack、queue
@我漫长的孤独流浪6 小时前
数据结构测试模拟题(2)
数据结构·c++·算法