您的位置:首页 > 编程语言 > C语言/C++

C++11 <regex>

2015-12-09 22:39 351 查看
/*
C++ 的正则表达式的库,初次感觉不是很好用,也许是个人还不太熟悉的原因吧!!!
主要是分三部分:
1 模式
2 容器
3 操作

1 模式:正则表达式的匹配就是“字符串模式”匹配,只不过正则表达式中有些字符是有特定的含义的,模式依据字符类型分成两类:
std::regex: 针对 char* 和 string
std::wregex: 针对 wchar_t* 和 wstring
2 容器:匹配总会有个结果,这些结果需要保存下来,依据字符表示方法和字符类型分成四类:
std::cmatch: 针对 char*
std::smatch: 针对 string
std::wcmatch: 针对 wchar_t*
std::wsmatch: 针对 wstring
3 操作 依据操作类型,分成三类:
 std::regex_match: 查找所有的匹配结果
 std::regex_serach:
 std::regex_replace:
*/


代码如下:

// regex_match example
#include <iostream>
#include <regex>
#include <string>

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: