#include <regex>
#include <string>
#include <iostream>
//简单使用(实际可以有更多参数):
//regex_search, regex_match
//两个参数时:第一个为待匹配字符串string对象,第二个为匹配模板regex对象
//三个参数时:第一个为string对象,第二个为匹配结果容器smatch对象,第三个为regex对象
//regex_replace
//三个参数时:第一个为string对象,第二个为regex对象,第三个为替换字符串string对象
int main()
{
// 是否匹配整个序列
std::cout << (std::regex_match("6666a", std::regex("[0-9]+")) ? "True" : "False")
<< std::endl;
// 是否包含所需字段
std::cout << (std::regex_search("666a", std::regex("[0-9]+")) ? "True" : "False")
<< std::endl << std::endl;
// regex匹配,res_M[0]为匹配结果,res_M[1]为结果的第一个分组
std::string str = "Hello, regex in C++!";
std::regex pattern(".*(C\\+\\+).*");
std::smatch res_M;
std::regex_match(str, res_M, pattern);
for (int count = 0; count < res_M.size(); count++)
std::cout << "res_M[" << count << "]: " << res_M[count] << " "
<< std::endl;
std::cout << std::endl;
// regex搜索,可用于获取多次匹配结果,res_S[0]为匹配结果,未使用分组,故count始终为0
str = "Hello, regex in C++!";
pattern = std::regex("[A-Z][a-z]*");
std::smatch res_S;
while (std::regex_search(str, res_S, pattern))
{
for (int count = 0; count < res_S.size(); count++)
std::cout << "res_S[" << count << "]: " << res_S[count] << " ";
std::cout << std::endl;
str = res_S.suffix().str();
std::cout << "str: " << str << std::endl;
}
std::cout << std::endl;
//regex替换, 将搜索到的结果进行替换,返回替换后的字符串,$1表示搜索结果的第一个分组
str = "Hello, regex in C++!";
pattern = std::regex("([A-Z][a-z]+)");
std::string str_R = "$1, my friend";
str = std::regex_replace(str, pattern, str_R);
std::cout << "Replaced string: " <<str << std::endl;
return 0;
}
输出结果:
False
True
res_M[0]: Hello, regex in C++!
res_M[1]: C++
res_S[0]: Hello
str: , regex in C++!
res_S[0]: C
str: ++!
Replaced string: Hello, my friend, regex in C++!