在程序开发时,我们有时遇需要过滤一些特殊字符,或者匹配一些固定的字符等,比如电话号码都是数字,电子邮箱包含@符号,密码不能包含特殊字符等,这些都是可以用正则表达式来实现,很多高级语言都提供这个库比如python,java等C++11之前没有这个库所以处理这些很麻烦,从c++11开始就提供了正则表达式的库在头文件regex中。
函数 | |
(C++11) | 尝试匹配一个正则表达式到整个字符序列 (函数模板) |
(C++11) | 尝试匹配一个正则表达式到字符序列的任何部分 (函数模板) |
(C++11) | 以格式化的替换文本来替换正则表达式匹配的出现位置 (函数模板) |
下面我们看它的一些简单示例。
1.regex_match的使用
#include <iostream>
#include <regex>
using namespace std;
//regex_match
int main()
{
//1.尝试匹配一个正则表达式到整个字符序列,若匹配存在则返回true,否则返回false.
//1.1 简单正则表达式匹配
std::string fnames[] = {"yak.txt", "scott.txt", "yak.txt", "run.dat", "caleml"};
std::regex txt_regex("[a-z]+\\.txt");
for(const auto &fname: fnames)
{
cout << fname << ": " << regex_match(fname, txt_regex) << endl;
}
cout << endl;
//1.2提取子匹配
regex base_regex("([a-z]+)\\.txt");
smatch base_match;
for(const auto &fname: fnames)
{
if(regex_match(fname, base_match, base_regex))
{
cout << fname << " base_match.size() " << base_match.size() << endl;
//首个sub_match是整个字符串,下个sub_match是首个括号表达式。
if(base_match.size() == 2)
{
ssub_match base_sub_math = base_match[1];
string base = base_sub_math.str();
cout << fname << " has a base of " << base << endl;
}
}
}
cout << endl;
//3. 提取几个子匹配
std::regex pieces_regex("([a-z]+)\\.([a-z]+)");
std::smatch pieces_match;
for (const auto &fname : fnames)
{
if (std::regex_match(fname, pieces_match, pieces_regex))
{
std::cout << fname << endl;
for (size_t i = 0; i < pieces_match.size(); ++i)
{
std::ssub_match sub_match = pieces_match[i];
std::string piece = sub_match.str();
std::cout << " submatch " << i << ": " << piece << '\n';
}
}
}
cout << "Hello World!" << endl;
return 0;
}
运行结果:
2.regex_search
#include <iostream>
#include <regex>
using namespace std;
//regex_search
int main()
{
string target("baaaby");
smatch sm;
regex re1("a(a)*b");
regex_search(target, sm, re1);
cout << "entire match: " << sm.str(0) << '\n'
<< "submatch #1: " << sm.str(1) << '\n';
regex re2("a(a*)b");
regex_search(target, sm, re2);
cout << "entire match: " << sm.str(0) << '\n'
<< "submatch #1: " << sm.str(1) << '\n';
cout << "hello world!" << endl;
return 0;
}
运行结果:
3.regex_replace
#include <iostream>
#include <regex>
using namespace std;
int main()
{
string text = "Quick brown fox";
regex vowel_re("a|e|i|o|u");
// 写结果到输出迭代器
regex_replace(std::ostreambuf_iterator<char>(std::cout),
text.begin(), text.end(), vowel_re, "*");
// 构造保有结果的字符串
cout << '\n' << std::regex_replace(text, vowel_re, "[$&]") << endl;
cout << "hello world!" << endl;
return 0;
}
运行结果:
参考: