c++++ regex 库提供了一种机制来处理正则表达式:创建 regex 对象来表示正则表达式模式。使用 regex_match 匹配整个字符串。使用 regex_search 匹配字符串中的第一个子串。使用 regex_replace 用替换字符串替换匹配的子串。
使用 C++ 函数库进行正则表达式匹配
引言
正则表达式是一种强大且通用的模式匹配机制,可用于从文本中搜索和提取特定模式。C++ 标准函数库提供了一组称为 regular expressions(regex)库的函数,可用于处理正则表达式。
regex 库
regex 库包含以下关键类和函数:
- regex: 表示正则表达式模式。
- regex_match: 匹配整个字符串。
- regex_search: 匹配字符串中第一个子串。
- regex_replace: 用替换字符串替换匹配的子串。
使用示例
下面是一个用 regex 库匹配正则表达式的代码示例:
#include <regex> #include <iostream> int main() { // 要匹配的字符串 std::string text = "abcdefghi"; // 匹配包含字母 "b" 的子串 std::regex re("[a-z]*b[a-z]*"); // 使用 regex_search 匹配 text std::smatch m; if (regex_search(text, m, re)) { std::cout << "匹配成功: " << m.str() << std::endl; } else { std::cout << "匹配失败" << std::endl; } return 0; }