简介
定义于头文件<regex>
正则表达式库提供表示正则表达
的类,正则表达式是一种用于在字符串中匹配模式的微型语言。下列数种对象上的操作能刻画几乎所有带正则表达式的操作:
- 目标序列。为模式而搜索到的字符序列。这可以是二个迭代器所指定的范围、空终止字符串或一个
std::string
。 - 模式。这是正则表达式自身。它确定构成匹配者。它是从带特定语法的字符串构成的
std::basic_regex
类型对象。受支持的语法变体的描述见syntax_option_type
。 - 匹配的数组。关于匹配的信息可作为
std::match_results
类型对象获取。 - 替换字符串。这是确定如何替换匹配的字符串,受支持的语法变体的描述见
match_flag_type
。
主类
类名 | 备注 |
---|---|
basic_regex | 正则表达式对象 |
sub_match | 标识子表达式所匹配的字符序列 |
match_results | 标识一个正则表达式匹配,包含所有子表达式匹配 |
算法
这些算法将封装于 regex 的正则表达式应用到字符的目标序列。
函数名 | 备注 |
---|---|
regex_match | 试图匹配正则表达式到整个字符序列 |
regex_search | 试图匹配正则表达式到字符序列的任何部分 |
regex_replace | 以格式化的替换文本来替换正则表达式匹配的出现位置 |
迭代器
regex_iterator 用于遍历在序列中找到的匹配正则表达式的整个集合。
类名 | 备注 |
---|---|
regex_iterator | 在字符序列中通过所有正则表达式匹配迭代 |
regex_token_iterator | 通过在给定的字符串中所有正则表达式匹配中的指定子表达式,或通过不匹配的子串迭代 |
异常
此类定义作为异常抛出以报告来自正则表达式库错误的类型。
类名 | 备注 |
---|---|
regex_error | 报告正则表达式库生成的错误 |
示例&输出
- 实例
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
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 << "Text contains the phrase 'regular expressions'\n";
}
std::regex word_regex("(\\S+)");
auto words_begin =
std::sregex_iterator(s.begin(), s.end(), word_regex);
auto words_end = std::sregex_iterator();
std::cout << "Found "
<< std::distance(words_begin, words_end)
<< " words\n";
const int N = 6;
std::cout << "Words longer than " << N << " characters:\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';
}
- 输出
Text contains the phrase ‘regular expressions’
Found 19 words
Words longer than 6 characters:
people,
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].