正則表達式使用規則:
*在c++z中使用轉義符號都要雙寫不管是\w,還是普通的符號,例如\\w,\\.
1.單個內容的匹配符號:
. :是針對除了換行符以外的任意一個字符.
\w:字母(大小寫),數字,下划線(\W是除了\w之外的符號)
\d:數字(\D是非數字)
\s:空白符(空格,制表,換行)(大寫同上)
\b:聲明一個邊界
[ ]:匹配指定字符(例如:[a-z\A-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這種在輸入時要變成\\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; }