boost的正则表达式库是目前C++开发中普遍用到的库,下面列举regex_search的用法,该用法是搜寻指定regex expression在文本中所有能够匹配的部分,注意,regex expression中的 / 要注意变成 //进行转义
- #include <iostream>
- #include <boost/regex.hpp>
- using namespace std;
- int main( int argc, char* argv[] )
- {
- string buf = "This is and 1=1 example or 2>1";
- boost::regex exampleregex("(and|or)//s+[0-9]+//s*(>|<|=|<>|!=)//s*[0-9]+");
- std::string::const_iterator start, end;
- start = buf.begin();
- end = buf.end();
- boost::match_results<std::string::const_iterator> what;
- boost::match_flag_type flags = boost::match_default;
- while(boost::regex_search(start,end,what,exampleregex,flags))
- {
- cout<<string(what[0].first,what[0].second)<<endl;
- start = what[0].second;
- }
- system("pause");
- return 0;
- }