正则表达式:正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。
#include<regex>
基本类型
basic_regex
typedef basic_regex<char> regex;
typedef basic_regex<wchar_t> wregex; //用于wstring匹配
basic_regex实例化
std::regex("/bed/\\d{1,3}"); //两个反斜杠是因为字符串的\会先转义
构造函数中还有一个默认参数flags,默认值为 std::regex::ECMAScript,该参数可以用来设置正则表达式所采用的语法。还可以设置 case insensitive
std::regex ninth ("/bed/\\d{1,3}", ECMAScript | icase );//忽略大小写
匹配结果
match_results
是一种 container-like 的模板类,用于存放对目标串执行完 regex matching 操作后匹配到的结果,其中的每个元素(即每个匹配结果)是一个 sub_match 的实例化对象。
typedef match_results<const char*> cmatch;
typedef match_results<const wchar_t*> wcmatch;
typedef match_results<string::const_iterator> smatch;
typedef match_results<wstring::const_iterator> wsmatch;
根据一次匹配的结果,match_results 可能为空也可能不空,使用match_results::empty()
来判空,使用match_results::size()
来获取元素个数。对于一个不空的 match_results 对象,其第一个 sub_match 元素([0])对应着整个完整匹配,后续的元素对应着正则表达式中的 sub-match
res[0]: abc def //总共匹配到两个
res[1]: abc
res[2]: def
sub_match
对象存储的不是匹配到的字符串本身,而是指向这个串开始(initial)和结束后一个字符(past-the-end)的 bidirectional iterators,但是它们表现起来类似于一个字符串
成员函数 length
返回字符串长度;
compare
用于和一个字符串或另一个 sub_match 对象比较,相等则返回0,不等则:若它比参数小(字典序)返回一个负值,否则返回一个正值;
str
返回对应的字符串。
与match_result
对应的四种实例化方式
typedef sub_match<const char*> csub_match;
typedef sub_match<const wchar_t*> wcsub_match;
typedef sub_match<string::const_iterator> ssub_match;
typedef sub_match<wstring::const_iterator> wssub_match;
正则操作
regex_match
:全文匹配,要求整个字符串符合正则表达式的匹配规则。返回bool类型。
bool regex_match(str,regex,flags);
regex_search
:搜索匹配,根据正则表达式来搜索字符串中是否存在符合规则的子字符串。
bool regex_search(str, smatch, regex);
regex_replace
:替换匹配,即可以将符合匹配规则的子字符串替换为其他字符串。
std::string::iterator regex_replace(str, regex, fmt, flags); //fmt 替换的文本