正则表达式使用规则:
*在c++z中使用转义符号都要双写不管是w,还是普通的符号,例如\w,\.
1.单个内容的匹配符号:
. :是针对除了换行符以外的任意一个字符.
w:字母(大小写),数字,下划线(W是除了w之外的符号)
d:数字(D是非数字)
s:空白符(空格,制表,换行)(大写同上)
:声明一个边界
[ ]:匹配指定字符(例如:[a-zA-Z1-9]是匹配小写字母大写字母,""以及数字的一个字符)(匹配汉字的方法使用万国码[u4e00-u9fa5])
2.匹配的字符个数:(用在单个限定样式的字符后面)
+:匹配一个或多个字符
*:匹配零个或是多个字符
?:匹配零个或是一个字符
{ }:匹配指定次数(例如{1,3}字符重复一次或是3次,也可以{3}只重复3次)
3.分组匹配
我们只需要把我们所需要的分组加上括号,之后我们可以通过smatch变量寻找( 该变量的列表中第一个元素永远是执行匹配操作的原始字符串,smatch mat,mat[1].str分组第一组 ).括号还有就是(jpg|bmp)的作用
正则表达式函数调用:
regex_match()对字符串进行匹配(一般不使用,因为字符串匹配的正则表达式要考虑到整个字符串)
使用regex_search()对字符串进行循环寻找:
正则表达式在对大量字符串的提取有效信息,所支持的头文件#include <regex>
regex_match:将一个字符序列与一个正则表达式匹配
regex_search:寻找第一个与正则表达式匹配的子序列
regex_replace:使用给定格式替换一个正则表达式
sregex_iterator:迭代器适配器,调用regex_search来遍历一个string中所有匹配的字串
这里要注意的是这种在输入时要变成\b,这里的+代表一直找d知道遇到 '.'(如果我们只想找n个数字只需要把+换{n}即可),{1}代表着上面的组只循环一次
循环搜索:
string test = "145341.35186410.200034uhvsv nfji7676876///1324531.1"; smatch mat; regex rgx("(\d+\.){1}"); string::const_iterator start = test.begin(); string::const_iterator end = test.end(); while (regex_search(start, end, mat, rgx)) { cout << mat[1].str() << endl; start = mat[0].second; }
输出结果:循环输出
下面是正则一些函数的使用方法:
int main(){ //第一种存储方式 //match_results<string::const_iterator> result; //第二种存储方式 smatch result; //文本数据 string str="1994 is my birth year 1994"; //正则表达式 string regex_str("\d{4}"); regex pattern1(regex_str,regex::icase); //迭代器声明 string::const_iterator iter = str.begin(); string::const_iterator iterEnd= str.end(); string temp; //正则查找 while (std::regex_search(iter,iterEnd,result,pattern1)) { temp=result[0]; cout<<temp<<endl; iter = result[0].second; //更新搜索起始位置 } //正则匹配 string regex_str2("(\d{4}).*"); regex pattern2(regex_str2,regex::icase); if(regex_match(str,result,pattern2)){ cout<<result[0]<<endl; cout<<result[1]<<endl; } //正则替换 std::regex reg1("\d{4}"); string t("1993"); str = regex_replace(str,reg1,t); //trim_left cout<<str<<endl; return 0; }