C++11 正则表达式
1、验证整个字符串是否符合给定正则表达式
2、在字符串中查找符合给定正则表达式的子串
3、在字符串中查找符合正则表达式的子串,并替换
上述三点分别对应C++11中的三个函数,包含头文件#include <regex>
验证整个字符串是否符合给定正则表达式
使用函数std::regex_match(),一般都是分三步:
1、定义正则表达式 std::regex 类,将正则表达式的字符串形式传入其构造函数进行实例化;
2、定义std::smatch matchResult用来存放匹配结果,对应正则表达式中的括号,一般一个括号为一个子表达式,可以作为参数传入函数第3步的函数,也可以不传,省略;
3、调用std::regex_match()函数,匹配成功返回true。
调用std::regex_match()函数,匹配成功返回true。
//定义正则表达式,下面iStr为string类型
std::regex reg("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
std::smatch matchResult;//存放匹配成功时正则表达式中各个子表达式对应的实际字符串,下标为0是整个正则表达式对应的字符串
//以枚举形式重载的函数
if (std::regex_match((string::const_iterator)iStr.begin(), (string::const_iterator)iStr.end(), matchResult, reg))
{
return true;
}
//另一个重载函数
if (std::regex_match(iStr, matchResult, reg))
{
return true;
}
//regex_match()函数std::smatch类型参数可以省略,例如,但此参数在循环调用regex_search()函数时十分
if (std::regex_match(iStr, reg))
{
return true;
}
在字符串中查找符合给定正则表达式的子串
使用函数std::regex_match(),一般都是分三步:
1、定义正则表达式 std::regex 类,将正则表达式的字符串形式传入其构造函数进行实例化;
2、定义std::smatch matchResult用来存放匹配结果,matchResult[0]对应整个正则表达式的匹配结果,matchResult[1]对应正则表达式的第一个括号(第一个子表达式)的匹配结果,以此类推;
3、调用std::regex_match()函数,匹配成功返回true。
步骤和上述类似,只不过第3步调用函数std::regex_search(),要返回所有符合正则表达式的子串,可以在while循环中实现:
std::regex reg("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
string iStr = "192.168.1.1";
std::smatch matchResult;
string::const_iterator iterator = iStr.begin();
string::const_iterator iteratorEnd = iStr.end();
while (std::regex_search(iterator, iteratorEnd, matchResult, reg))
{
//matchResult[0] 代表的是匹配成功后整个正则表达式对应的字符串
cout << matchResult[0] << endl;
//返回的枚举是下一个循环要用的枚举,不要直接iterator++,这样写效率低
iterator = matchResult[0].second;
}
在字符串中查找符合正则表达式的子串,并替换
注意,regex_replace()函数会替换所有符合给定正则表达式的子串,例如下例输出结果为:"111111"
std::regex reg("[A-Za-z]");
string iStr = "abcdef";
//std::smatch matchResult;
string::const_iterator iterator = iStr.begin();
string::const_iterator iteratorEnd = iStr.end();
string result = std::regex_replace(iStr, reg, "1");
cout << result;
详细请参考:
https://www.cnblogs.com/cmranger/p/4753668.html