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;
- }
本文介绍了一段使用Boost库中的正则表达式搜索特定模式的C++代码示例。通过一个具体的例子展示了如何在字符串中查找符合预定义正则表达式的部分,并逐一输出匹配项。
5847

被折叠的 条评论
为什么被折叠?



