正則表達式(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
作者:csdn博客 Spike_King