早就知道C++11標(biāo)準(zhǔn)增加了regex支持,昨天在VS2015試了下,很好用~
今天在linux的G++上一試,發(fā)現(xiàn)G++就是坑啊,一編譯運(yùn)行直接拋出regex_error異常贯涎,這才知道。G++到4.9才支持regex慢洋,以前就只是個(gè)殼子…塘雳, 更新到4.9.3后就能正常使用了~
其中主要的算法為regex_search, regex_match, regex_replace.
下面是一個(gè)簡單的示例
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main() {
// 是否匹配整個(gè)序列,第一個(gè)參數(shù)為被匹配的str普筹,第二個(gè)參數(shù)為regex對(duì)象
cout << regex_match("123", regex("[0-9]+")) << endl;
// regex搜索
string str = "subject";
regex re("(sub)(.*)");
smatch sm; // 存放string結(jié)果的容器
regex_match(str, sm, re);
for(int i = 0; i < sm.size(); ++i)
cout << sm[i] << " ";
cout << endl;
// regex搜索多次
str = "!!!123!!!12333!!!890!!!";
re = regex("[0-9]+");
while(regex_search(str, sm, re)) {
for(int i = 0; i < sm.size(); ++i)
cout << sm[i] << " ";
cout << endl;
str = sm.suffix().str();
}
return 0;
}