C++11 Regex正则表达式初探

早就知道C++11标准增加了regex支持,昨天在VS2015试了下,很好用~

今天在linux的G++上一试,发现G++就是坑啊,一编译运行直接抛出regex_error异常,这才知道。G++到4.9才支持regex,以前就只是个壳子…, 更新到4.9.3后就能正常使用了~

其中主要的算法为regex_search, regex_match, regex_replace.

链接:一个比较好的regex参考

下面是一个简单的示例

#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;
}
原文地址:https://www.cnblogs.com/kunsoft/p/13675299.html