C++11開始支持正則表達式,使得處理文本更加簡潔方便。C++11 支持六種正則表達式語法:ECMAScript, basic(POSIX Basic Regular Expressions), extended(POSIX Extended Regular Expressions ), awk(POSIX awk) , grep(POSIX grep ), egrep(POSIX grep –E)。其中ECMAScript最為強大。
閑話不多說,首先來看正則表達式有哪些基本類型。
- basic_regex: 這是一個包含一個正則表達式的模板類。通常有兩種特化方式:
a) typedef basic_regex<char> regex;
b) typedef basic_regex<wchar_t> wregex;
2. match_results: 這個類包含了與給定正則表達式匹配的序列。當empty()成員返回true或者size()成員返回0,表明沒有找到匹配項。否則,當empty()返回false,size()返回值>=1 表明發生了匹配。此外:match[0]: 代表整個匹配序列 ;match[1]:代表第一個匹配子序列 ;match[2]: 代表第二個匹配子序列,以此類推。match_results有如下特化方式:
a) typedef match_results<const char*> cmatch;
b) typedef match_results<const wchar_t*> wcmatch;
c) typedef match_results<string::const_iterator> smatch;
d) typedef match_results<wstring::const_iterator> wsmatch;
3. sub_match: 該模板類用來表示與一個已標記的子表達式匹配的序列。這個匹配是通過一個迭代器對來表示的,該迭代器對表明了已匹配的正則表達式的一個范圍。可以特化為下面幾種情況:
a) typedef sub_match<const char*> csub_match;
b) typedef sub_match<const wchar_t*> wcsub_match;
c) typedef sub_match<string::const_iterator> ssub_match;
d) typedef sub_match<wstring::const_iterator> wssub_match;
以上介紹了一種常用的類型,敘述可能比較抽象,后面會結合例子來介紹這些類型的用法,還是會比較好理解。
然后來認識一下操作正則表達式的一些常用算法。
template <class charT,class Allocator,class traits >
bool regex_match(
const charT* str,
match_results<const charT*,Allocator>& m,
const basic_regex<charT,traits >& e,
match_flag_type flags = match_default);
regex_match 判斷一個正則表達式(參數 e)是否匹配整個字符序列 str. 它主要用於驗證文本。注意,這個正則表達式必須匹配被分析串的全部,否則函數返回 false. 如果整個序列被成功匹配,regex_match 返回 True.
template <class traits,class charT>
basic_string<charT> regex_replace(
const basic_string<charT>& s,
const basic_regex<charT,traits >& e,
const basic_string<charT>& fmt,
match_flag_type flags = match_default);
regex_replace 在整個字符序列中查找正則表達式e的所有匹配。這個算法每次成功匹配后,就根據參數fmt對匹配字符串進行格式化。缺省情況下,不匹配的文本不會被修改,即文本會被輸出但沒有改變。
template <class charT,class Allocator, class traits>
bool regex_search(
const charT* str,
match_results<const charT*,Allocator>& m,
const basic_regex<charT,traits >& e,
match_flag_type flags = match_default);
regex_search 類似於 regex_match, 但它不要求整個字符序列完全匹配。你可以用 regex_search 來查找輸入中的一個子序列,該子序列匹配正則表達式 e.
迭代器介紹:正則表達式迭代器用來遍歷這個正則表達式序列,通過一個迭代器區間來表示匹配的區間。
- regex_iterator:
a) typedef regex_iterator<const char*> cregex_iterator;
b) typedef regex_iterator<const wchar_t*> wcregex_iterator;
c) typedef regex_iterator<string::const_iterator> sregex_iterator;
d) typedef regex_iterator<wstring::const_iterator> wsregex_iterator;
2. regex_token_iterator:
a) typedef regex_token_iterator<const char*> cregex_token_iterator;
b) typedef regex_token_iterator<const wchar_t*> wcregex_token_iterator;
c) typedef regex_token_iterator<string::const_iterator> sregex_token_iterator;
d) typedef regex_token_iterator<wstring::const_iterator> wsregex_token_iterator;