提取标签之间的CString [英] Extract CString between tags
问题描述
如何在两个标签之间提取CString?
How can I extract a CString between two tags ?
<tag1>My Text</tag1>
我不想计算开始和结束位置,然后使用Mid,也许还有另一种使用STL的简便方法?
I don't want to calculate the start and end position then use Mid, maybe there is another easier method using STL ?
推荐答案
免责声明:以下想法是不能在生产代码中使用.我假设您只是想快速进行测试.
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.
使用正则表达式匹配标签. Microsoft在CAtlRegExp中提供了此功能.如果您使用的是Visual Studio 2008或更高版本,请在此处下载ATL .然后,只需在下面的代码中提供myString
:
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
}
}
免责声明2:您确实应该使用 XML解析器库.
Disclaimer 2: You really should use an XML parser library instead.
这篇关于提取标签之间的CString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!