您的位置:首页 > 编程语言 > C语言/C++

C++11 正则表达式——基础知识介绍

2013-07-14 10:41 295 查看
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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: