c++11正则表达式入门

来源:互联网 发布:淘宝买二手书看可以吗 编辑:程序博客网 时间:2024/05/22 10:51
#include <iostream>#include <regex>#include <exception>#include <wchar.h>namespace std{typedef basic_regex<wchar_t> wregex;}int main(){// 1.规则std::regex rx;try{// ?等价于匹配长度{0,1}// *等价于匹配长度{0,} // +等价于匹配长度{1,}// 转义字符等价\w \W \d \D \. \\,但是注意c++中要使用\\w, \\W, \\d, \\D, \\\\rx = "^[a-zA-Z]{0,}\\.doc$";// {0,}等价于*,表示零个以上,以.doc结尾rx = "[^0-9]{0,}";// 不包含0-9的零个以上个字符([]中放开头的^表示不等于,若不放开头为普通字符)rx = "^abc[a-zA-Z]*abc$";// ^abc表示以abc开始,abc$表示以abc结束rx = "^1827918[0-9]{4}$";// 以1827918开头,后接四位数字结束rx = "^abc[0-9a-zA-Z_]*cba$";// 以abc开头,中间添加[0-9a-zA-Z_]范围内的数,后接cba结束// 好像表示开头和结尾的^和$都没什么用rx = "[-+]*[0-9]*\\.?[0-9]*";// 数rx = ".*";// .表示任何单位字符(全部范围)rx = "[0-9a-zA-Z_]+\\.txt";// 非空文件名的txt}catch (std::exception & e){std::cout << e.what() << std::endl;exit(EXIT_FAILURE);}std::string s;while (std::cin >> s){std::cout << std::boolalpha << std::regex_match(s, rx) << std::endl;}// 2.对wchar_tstd::wstring ws;std::wregex wrx;// wregex是basic_regex<wchar_t>的typedeftry{wrx = L"[-+]{0,}\\.?[0-9]{0,}";}catch (std::exception & e){std::cout << e.what() << std::endl;}while (std::wcin >> ws){std::cout << std::boolalpha << std::regex_match(ws, wrx) << std::endl;}// 3.特别说明对\\,对字符串中的\\,正则中用\\\\匹配字符串中的\\。wchar_t * path = L"E:\\dir2\\p1.jpg";std::wregex wrx2(L"[a-zA-Z]{1}:\\\\[^^%&',;=?$\"<>:]*\\.jpg");std::cout << std::boolalpha << std::regex_match(path, wrx2) << std::endl;wrx2 = L"[a-zA-Z]{1}:\\\\[^^%&',;=?$\"<>:\\\\]*\\.jpg";// 不允许在盘符下的子目录中。判断是否有\\用\\\\匹配std::cout << std::boolalpha << std::regex_match(path, wrx2) << std::endl;return 0;}

0 0
原创粉丝点击