C++正则表达式

来源:互联网 发布:ubuntu 阿里云 dns设置 编辑:程序博客网 时间:2024/06/06 14:05

需要引入库函数

#include<regex>

* 可以进行字符串的匹配
* 对于正则表达式出现的问题(正则表达式写错之类的),可以通过try、catch来捕捉异常
* 可以通过搜索,得到第一个匹配的子串或者通过迭代器,得到所有匹配的子串。

代码

#include<iostream>#include<exception>#include<fstream>#include<sstream>#include<string>#include<vector>#include<iterator>#include<list>#include<deque>#include<stack>#include<queue>#include<concurrent_priority_queue.h>#include<algorithm>#include<numeric>#include<functional>  //bind#include<map>#include<set>#include<unordered_map>#include<memory>#include<assert.h>#include<tuple>#include<regex>using namespace std;int main(){    cout << "start!" << endl;    string pattern("[^c]ei");    pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";    regex r(pattern);    smatch results;    string test_str = "receipt freind theif receive";    //输出第一个匹配的子串    if (regex_search(test_str, results, r))    {        cout << results.str() << endl;    }    //输出所有匹配的子串    for (sregex_iterator it(test_str.begin(), test_str.end(), r), end_it;        it != end_it; ++it)    {        cout << it->str() << endl;    }    try    {        regex r("[[:alnum:]", regex::icase);    }    catch ( regex_error e )    {        cout << e.what() << endl << e.code() << endl;    }    cout << "end!" << endl;    system("pause");    return EXIT_SUCCESS;}
0 0
原创粉丝点击