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

比如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");
}

输出:

所以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");
}

原文:https://cv2022.blog.csdn.net/article/details/118189334

posted @ 2022-06-21 10:08  萧海~  阅读(406)  评论(0编辑  收藏  举报