0
点赞
收藏
分享

微信扫一扫

C++正则匹配实现提取两个指定字符串之间的字符串

hwwjian 2022-09-16 阅读 161

比如Known=4325,guid=qwer233,Element=fdger2354, 把guid=后面的qwer233给提取出来。

即提取“guid=”和“,”之间的字符串。

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main()
{
string text = "Known=4325,guid=qwer233,Element=fdger2354,";
cout << text << endl;
regex pattern(".*?guid=(.*?),.*?");
smatch results;
if (regex_match(text, results, pattern))
for (auto it = results.begin(); it != results.end(); ++it)
cout << *it << endl;
else
cout << "match failed: " << text << endl;
system("pause");
}

输出:

C++正则匹配实现提取两个指定字符串之间的字符串_#include

所以results[1]就是我们要的值 。

你要把函数封装起来也行:

#include <iostream>
#include <string>
#include <regex>
using namespace std;

string midstr(string oldstr, string startstr, string endstr)
{
string re = ".*?" + startstr + "(.*?)" + endstr + ".*?";
regex pattern(re);
smatch results;
if (regex_match(oldstr, results, pattern))
return results[1];
else
cout << "match failed: " << oldstr << endl;

}


int main()
{
string text = "Known=4325,guid=qwer233,Element=fdger2354,";
string data;
data = midstr(text, "guid=", ",");
cout << data << endl;
system("pause");
}

举报

相关推荐

0 条评论