正则表达式(regex) 迭代器(iterator) 的 详解 及 代码
本文地址: http://blog.csdn.net/caroline_wendy/article/details/17319899
正则表达式(regex), 使用boost的regex头文件, 是C++11的新标准, 但是gcc4.8.1并未完全支持, 所以使用boost库;
具体安装: http://blog.csdn.net/caroline_wendy/article/details/17282187
正则表达式的书写规范, 以ECMAScript为例, 使用迭代器可以遍历原字符串, 输出符合要求的所有字符串;
使用prefix()和suffix()方法, 可以输出前一个未匹配的字符串和后一个未匹配的字符串;
正则表达式的子表达式(subexpressions), 可以分段输出正则表达式, 在正则表达式中, 以括号"()"分解;
代码如下:
#include <iostream> #include <string> #include <algorithm> #include <boost/regex.hpp> using namespace std; using namespace boost; int main() { std::string pattern("[^c]ei"); pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*"; boost::regex r(pattern, regex::icase); //忽略大小写 std::string str("Ruby Carolinei biubiubiu Weindy SpikeI Winnceiy"); //使用正则迭代器进行遍历 for(boost::sregex_iterator it(str.begin(), str.end(), r), end_it; it!=end_it; ++it) std::cout << it->str() << std::endl; //输出正则表达式的前后字符串 std::cout << std::endl; for(boost::sregex_iterator it(str.begin(), str.end(), r), end_it; it!=end_it; ++it){ auto pos = it->prefix().length(); pos = pos>40 ? pos-40 : 0; std::cout << it->prefix().str().substr(pos) /*输出前一个未匹配的字符串*/ << "\n\t\t>>>" << it->str() << "<<<\n" << it->suffix().str().substr(0, 40) /*输出之后的字符串*/ <<std::endl; } //匹配子表达式 std::string filename("File.cqp MyGod.cpP"); boost::regex rsub("([[:alnum:]]+)\\.(cpp|cxx|cc)$", regex::icase); smatch results; if(boost::regex_search(filename, results, rsub)) std::cout << results.str(1) << std::endl; }
输出:
Carolinei Weindy SpikeI Ruby >>>Carolinei<<< biubiubiu Weindy SpikeI Winnceiy biubiubiu >>>Weindy<<< SpikeI Winnceiy >>>SpikeI<<< Winnceiy MyGod
转载于:https://blog.51cto.com/spikeking/1387957