早就知道C++11標準增加了regex支持,昨天在VS2015試了下,很好用~
今天在linux的G++上一試,發現G++就是坑啊,一編譯運行直接拋出regex_error異常,這才知道。G++到4.9才支持regex,以前就只是個殼子…, 更新到4.9.3後就能正常使用了~
其中主要的算法爲regex_search, regex_match, regex_replace.
下面是一個簡單的示例
#include <regex>
#include <string>
#include <iostream>
using namespace std;
int main() {
// 是否匹配整個序列,第一個參數爲被匹配的str,第二個參數爲regex對象
cout << regex_match("123", regex("[0-9]+")) << endl;
// regex搜索
string str = "subject";
regex re("(sub)(.*)");
smatch sm; // 存放string結果的容器
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;
}