STL 正则表达式 提取、替换
提取
regex_search:
//传入文件全路径,返回账户下的相对路径,截取部分符合条件的字符串返回
gchar *getlocaladdress(gchar *file_path)
{
//icase: case insensitive 不区分大小写
//匹配 xxx@xxx.xxx 的内容
std::regex r(".*@[[:alnum:]]+\\.[[:alpha:]]+/(.*)", std::regex::icase);
std::smatch results;
std::string str = std::string(file_path);
if(std::regex_search(str, results, r))
{
gchar *str = g_strdup(results.str(1).c_str());
return str;
}
return NULL;
}
替换
regexp_replace:
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string local_path("INBOX/hello");
string str("/home/sxd/.local/share/imap.163.com/24678@163.com/INBOX/.backup_mark");
regex r("(.*[[:alnum:]]+@[[:alnum:]]+\\.com/)(.*)", std::regex::icase);
string fmt = "$1" + local_path; //$1表示regex中第一个()的内容
cout << regex_replace(str, r, fmt) << endl;
return 0;
}
读取文件、提取并写入文件
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <regex>
using namespace std;
int main(int argc, char **argv)
{
ifstream in(argv[1]);
ofstream out(argv[2]);
vector<string> vs;
vector<string> outvs;
while(in) {
string tmpstr;
getline(in, tmpstr);
vs.push_back(tmpstr);
}
regex r(".*\\[Debug\\ \\ \\](.*)");
for(const string &s :vs) {
smatch result;
if(regex_match(s, result, r)) {
outvs.push_back(result.str(1));
}
}
for(auto s:outvs) {
out << s << endl;
}
return 0;
}