C++正则匹配实现提取两个指定字符串之间的字符串
Published on 2022-06-21 10:08 in 分类: C/C++ with 萧海~
分类: C/C++

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 @   萧海~  阅读(454)  评论(0编辑  收藏  举报
    相关博文:
    阅读排行:
    · winform 绘制太阳,地球,月球 运作规律
    · AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
    · 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
    · 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
    · 上周热点回顾(3.3-3.9)
    点击右上角即可分享
    微信分享提示
    电磁波切换