采用正则表达式处理XML标签

本文介绍了一个使用正则表达式实现的XML压缩算法,该算法能够识别并替换XML文件中的特定标签内容。通过定义一系列标签与替换字符串的映射,可以有效地简化XML文件,提高处理效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、采用正则表达式先匹配带的标签,
2、通过正则表达式匹配context。
3、后面可以处理context的内容。
注意:目前:context 只能为 英文字符 、数字 、_ 三种字符,如果需要支持不同的字符,可以通过修改正则表达式达到目标。

#include "stdafx.h"
#include<iostream>
#include<regex>
#include<map>
using namespace std;

wstring  XmlCompressByReplace( std::wstring inputXmlStr , std::map<std::wstring,std::wstring> markMap)
{
    std::wregex regTag(L"</?[^>]+/?>");          //匹配<context>
    std::wregex regTagContext(L"[0-9a-zA-Z-_]+");   // 匹配context

    std::wstring result;

    int pos = 0;
    while ((pos = inputXmlStr.find(L">")) != -1 )
    {
        std::wsmatch matchResult;

        wstring resultstr= inputXmlStr.substr(0, pos + 1);
        inputXmlStr = inputXmlStr.substr(pos + 1);

        std::wstring matchResultStr;
        if ( std::regex_search(resultstr, matchResult, regTag) )
        {
            matchResultStr = matchResult.str();
        }
        else
        {
            cout << "匹配错误!" << endl;//写日志
            return L"";
        }

        std::wstring matchResultContextStr;
        if ( std::regex_search(matchResultStr, matchResult, regTagContext) )
        {
            matchResultContextStr = matchResult.str();
        }
        else
        {
            cout << "匹配错误!" << endl;  //写日志
            return L"";
        }

        int start = matchResultStr.find(matchResultContextStr);
        wstring tempStr = matchResultStr;
        if (markMap[matchResultContextStr]==L"")
        {
            cout << "标签不存在!" << endl;  //写日志
            return L"";
        }
        matchResultStr.replace( start, matchResultContextStr.length(), markMap[matchResultContextStr] );
        start = resultstr.find(tempStr);
        resultstr.replace(start, tempStr.length(), matchResultStr);
        result += resultstr;
    }
    return result;
}

int main()
{  
    std::wstring text = L"<aa12>sd</aa12><bbbb>sdsd</bbbb><cccc/>";
    map<wstring, wstring> mak;
    mak[L"aa12"] = L"A";
    mak[L"bbbb"] = L"B";
    mak[L"cccc"] = L"C";
    wstring ss = XmlCompressByReplace(text, mak);
    wcout << ss << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值