Extract CString between tags

2019-08-20 03:15发布

问题:

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.