c++11之后封装了自己的正则表达式,直接包含文件即可使用,利用regex类声明对象初始化正则表达式,regex expressionName (“正则表达式”);正则表达式具体语法参考这里;regex_match()方法进行匹配,匹配成功返回1,失败返回0;cmatch和smatch类分别存放char*和string类型的结果,遍历即可获得;
// regex_match example
#include <iostream>
#include <string>
#include <regex>
int main ()
{
if (std::regex_match ("subject", std::regex("(sub)(.*)") ))
std::cout << "string literal matched\n";//字符串匹配
const char cstr[] = "subject";
std::string s ("subject");
std::regex e ("(sub)(.*)");
if (std::regex_match (s,e))
std::cout << "string object matched\n";//字符对象匹配
if ( std::regex_match ( s.begin(), s.end(), e ) )
std::cout << "range matched\n";//选择特定的位置进行匹配
std::cmatch cm; // same as std::match_results<const char*> cm;
std::regex_match (cstr,cm,e);
std::cout << "string literal with " << cm.size() << " matches\n";
std::smatch sm; // same as std::match_results<string::const_iterator> sm;
std::regex_match (s,sm,e);
std::cout << "string object with " << sm.size() << " matches\n";
std::regex_match ( s.cbegin(), s.cend(), sm, e);
std::cout << "range with " << sm.size() << " matches\n";
// using explicit flags:
std::regex_match ( cstr, cm, e, std::regex_constants::match_default );
std::cout << "the matches were: ";
for (unsigned i=0; i<sm.size(); ++i) {
std::cout << "[" << sm[i] << "] ";
}
std::cout << std::endl;
return 0;
}
小问题总结:
1.上图正则表达式的一些限制,如icase: Case insensitive(忽略大小写)regex expressionName (“正则表达式”,std::regex::icase).
2.正则表达式在c++代码中注意转义字符的使用,由于c++代码本身的转移功能,需要两次“\”的操作才能实现,如正则表达式需要匹配“\”,正则表达式为“\”,则咋c++代码中需要“\\”,第一个“\”转义说明第二个“\”为“\”,同理第三个“\”转义说明第四个“\”为“\”,获得正则表达式“\”.