正则是个很重要的东西,他有很多用处
这里我就发几个正则使用的代码
我们常用的3个函
regex_replace(替换),regex_match(匹配),regex_search(搜索)
首先是替换的,运行可以发现"我的博客:blog.icodef.com"替换成为了"我的博客:替换文本"
[cpp]
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex strRegex = "[a-z].{1,64}";
string strText("我的博客:blog.icodef.com");
regex r(strRegex );
string strReplace("替换文本");
cout << regex_replace(strText, r, strReplace) << endl;
return 0;
}
[/cpp]
这个可以把 blog.icodef.com 给取出来,然后直接输出
[cpp]
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex strRegex ("[a-z].{1,64}");
string strText("我的博客:blog.icodef.com");
cmatch result;
if (regex_search(strText.c_str(), result, strRegex , regex_constants::format_default)){
cout << result.str() << endl;
}
else{
cout << "false." << endl;
}
return 0;
}
[/cpp]
[cpp]
[/cpp]
这个是验证一个字符串是否可以匹配
[cpp]
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
regex strRegex ("[a-z].{1,64}");
string strText("我的博客:blog.icodef.com");
if (regex_match(strText.c_str(),strRegex)){
cout << "OK";
}
else{
cout << "Error";
}
return 0;
}
[/cpp]
文章评论