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; }
相关文章推荐
- 提高C++程序运行效率的10个简单方法
- 检查gcc编译器是否C++ 11特性
- [c++]单链表(class)
- C++左值引用和右值引用
- C语言易错点:字符串的连接
- Effective C++阅读笔记_条款2:尽量以const,enum,inline替换#define
- [C++] Test question(1-16)
- C语言:sizeof导致的Memory access violation
- 链表的分化问题(C++)
- 实战c++中的string系列--指定浮点数有效数字并转为string
- 实战c++中的string系列--指定浮点数有效数字并转为string
- (学习)C++ Primer(1)
- 实战c++中的string系列--string与整型或浮点型互转
- 实战c++中的string系列--string与整型或浮点型互转
- C语言快排模板 qsort();函数应用
- HDU2089 不要62【数位DP】
- c++ 11 右值引用原理
- 设计Qt风格的C++API
- C++ offsetof
- c语言的笔记