Extract CString between tags

家住魔仙堡 提交于 2019-12-12 01:45:17

问题


How can I extract a CString between two tags ?

 <tag1>My Text</tag1>

I don't want to calculate the start and end position then use Mid, maybe there is another easier method using STL ?


回答1:


Disclaimer: the following idea is bad and should not be used in production code. I'm assuming you just want a quick hack for testing.

Use a regular expression to match the tags. Microsoft provides this in CAtlRegExp. If you're using Visual Studio 2008 or newer, download ATL here. Then, just provide myString to the code below:

#include "atlrx.h"
CAtlRegExp<> regex;
VERIFY( REPARSE_ERROR_OK == regex.Parse("<tag1>(.*)</tag1>") );

CAtlREMatchContext<> mc;
if (!regex.Match(myString, &mc)) {
    // no match found
} else {
    // match(es) found
    for (UINT nGroupIndex = 0; nGroupIndex < mc.m_uNumGroups; ++nGroupIndex) {
        const CAtlREMatchContext<>::RECHAR* szStart = 0;
        const CAtlREMatchContext<>::RECHAR* szEnd = 0;
        mc.GetMatch(nGroupIndex, &szStart, &szEnd);
        ptrdiff_t nLength = szEnd - szStart;
        CString text(szStart, nLength);
        // now do something with text
    }
}

Disclaimer 2: You really should use an XML parser library instead.



来源:https://stackoverflow.com/questions/8658210/extract-cstring-between-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!