从C++11之后,C++开始支持正则表达式的使用。使用正则表达式时,需要引入regex头文件。正则表达式是一个非常强大的功能,它允许我们查找、匹配和替换匹配的字符子串。本文主要介绍下面3个正则函数:
函数名 | 作用 |
regex_match | 尝试匹配一个正则表达式到整个字符序列 |
regex_search | 尝试匹配一个正则表达式到字符序列的任何部分 |
regex_replace | 以格式化的替换文本来替换正则表达式匹配的出现位置 |
regex_match用于检查一个字符串是否完全匹配一个正则表达式。如果匹配,则返回true;否则返回false。regex_match可以分为不care匹配内容的版本和care匹配内容的版本。
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
std::regex pattern("([a-zA-Z]+)_([0-9]+)");
std::smatch m;
string my_str1 = "Hello_123";
string my_str2 = "Hello_123_1";
// regex_match只关心匹配结果,不关心匹配内容的版本
// matched.
cout << "my_str1 is matched: " << boolalpha
<< regex_match(my_str1, pattern) << endl;
// not matched.
cout << "my_str2 is matched: " << boolalpha
<< regex_match(my_str2, pattern) << endl;
// regex_match关心匹配内容的版本
if (regex_match(my_str1, m, pattern))
{
for(auto s: m)
{
cout << s << endl;
}
}
return 0;
}
运行结果如下:
my_str1 is matched: true
my_str2 is matched: false
Hello_123
Hello
123
regex_search用于检查一个字符串中能否查找到正则表达式所表示的子串。如果匹配,则返回true;否则返回false。和regex_match类似,可以分为不care匹配内容的版本和care匹配内容的版本。
#include <iostream>
#include <regex>
#include <string>
using namespace std;
int main()
{
std::regex pattern("([a-zA-Z]+)_([0-9]+)");
std::smatch m;
string my_str1 = "Hello_123";
string my_str2 = "Hello_123_1";
// regex_search只关心匹配结果,不关心匹配内容的版本
// searched.
cout << "my_str1 is searched: " << boolalpha
<< regex_search(my_str1, pattern) << endl;
// also searched.
cout << "my_str2 is searched: " << boolalpha
<< regex_search(my_str2, pattern) << endl;
// regex_search关心匹配内容的版本
if (regex_search(my_str1, m, pattern))
{
for(auto s: m)
{
cout << s << endl;
}
}
return 0;
}
运行结果如下,比较regex_match和regex_search两个程序的结果,不难发现,它们对同一个字符串my_str2的操作结果不同。这是因为,regex_match要求字符串完全匹配正则表达式,而regex_search只要查找有没有符合正则表达式的子串。
my_str1 is searched: true
my_str2 is searched: true
Hello_123
Hello
123
regex_replace是将符合正则表达是的子串用给定的字符串替换,并返回替换后的字符串。
#include <iostream>
#include <iterator>
#include <regex>
#include <string>
using namespace std;
int main()
{
std::regex pattern("[0-9]+");
string my_str1 = "Hello_123";
// 返回输出迭代器在所有插入后的副本
regex_replace(std::ostreambuf_iterator<char>(cout), my_str1.begin(), my_str1.end(), pattern, "world");
// 返回含有输出的字符串
cout << '\n' << regex_replace(my_str1, pattern, "world") << endl;
return 0;
}
运行结果如下:
Hello_world
Hello_world