概述
- 正则表达式是在c++11之后才被支持,叫正则表达式库。
- 使用的时候要包含<regex>头文件
正则表达式库
- 正则表达式有3个主要的算法
- regex_match
- regex_search
- regex_replace
- 既然出现在c++11版本,那么迭代器这一重要的特性肯定也是要有的
- regex_iterator
- regex_token_iterator
- 既然是正则表达式库,那么一定要熟悉c++正则表达式规则,和别的差不多。
- c++支持的正则表达式规则,自己从网上bd吧。
- 什么是正则表达式?就是用一个字符串描述一种特征,然后验证另一个字符串是否符合这个特征。
例子
#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';
}
- 这个例子演示了regex_search、迭代器、regex_replace的用法。
- regex_search和regex_match都是匹配函数。regex_search和regex_match的主要区别是:regex_match是全词匹配,而regex_search是搜索其中匹配的字符串。
- regex_search找到第一个就停止,不进行多次搜索。
- regex_replace进行多次搜索,将找到的匹配字符串替换成目标字符串。