正则表达式库 (C++11 起) - cppreference.com
来自cppreference.com
正则表达式库提供表示正则表达式的类,正则表达式是一种用于在字符串中匹配模式的微型语言。下列数种对象上的操作能刻画几乎所有带正则表达式的操作:
- 目标序列。为之搜索某个模式的字符序列。这可以是两个迭代器指定的范围、空终止字符串或一个 std::string。
- 模式。这是正则表达式自身。它决定由什么构成一个匹配。它是从带有专门文法的字符串构造的 std::basic_regex 类型对象。
- 匹配的数组。关于匹配的信息可作为 std::match_results 类型对象获取。
- 替换字符串。这是确定如何替换匹配的字符串。
正则表达式文法
模式和替换字符串支持以下的正则表达式文法:
- 有改动的 ECMAScript 正则表达式文法。默认使用此文法。
- 基本 POSIX 正则表达式文法。
- 扩展 POSIX 正则表达式文法。
- POSIX 中的 awk 工具所用的正则表达式文法。
- POSIX 中的 grep 工具所用的正则表达式文法。这相当于与基本 POSIX 正则表达式文法相同,附带将换行符
'\n'作为另一种分隔符。 - POSIX 中带
-E选项的grep工具所用的正则表达式文法。这相当于与扩展 POSIX 正则表达式文法相同,附带将换行符'\n'作为'|'之外的另一种分隔符。
另外还有一些文法变体(例如不区分大小写的匹配)可供使用,详情见此页。
主要类
这些类封装正则表达式和在字符的目标序列中匹配正则表达式的结果。
算法
这些函数用于将封装于 regex 的正则表达式应用到字符的目标序列。
迭代器
正则表达式迭代器用于遍历在序列中找到的整个正则表达式匹配集合。
异常
此类定义作为异常抛出以报告来自正则表达式库错误的类型。
特征
正则表达式特征类用于封装正则表达式的本地化方面。
常量
示例
#include <iostream> #include <iterator> #include <regex> #include <string> int main() { std::string s = "Some people, when confronted with a problem, think " "\"I know, I'll use regular expressions.\" " "Now they have two problems."; std::regex self_regex("REGULAR EXPRESSIONS", std::regex_constants::ECMAScript | std::regex_constants::icase); if (std::regex_search(s, self_regex)) std::cout << "文本包含短语 'regular expressions'\n"; std::regex word_regex("(\\w+)"); auto words_begin = std::sregex_iterator(s.begin(), s.end(), word_regex); auto words_end = std::sregex_iterator(); std::cout << "找到 " << std::distance(words_begin, words_end) << " 个单词\n"; const int N = 6; std::cout << "多于 " << N << " 个字符的单词:\n"; for (std::sregex_iterator i = words_begin; i != words_end; ++i) { std::smatch match = *i; std::string match_str = match.str(); if (match_str.size() > N) std::cout << " " << match_str << '\n'; } std::regex long_word_regex("(\\w{7,})"); std::string new_s = std::regex_replace(s, long_word_regex, "[$&]"); std::cout << new_s << '\n'; }
输出:
文本包含短语 'regular expressions' 找到 20 个单词 多于 6 个字符的单词: confronted problem regular expressions problems Some people, when [confronted] with a [problem], think "I know, I'll use [regular] [expressions]." Now they have two [problems].