提取标签之间的 CString

发布于 2024-12-23 05:14:49 字数 139 浏览 7 评论 0原文

如何提取两个标签之间的 CString ?

 <tag1>My Text</tag1>

我不想计算开始和结束位置然后使用 Mid,也许还有另一种更简单的方法使用 STL ?

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 ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

执笏见 2024-12-30 05:14:50

免责声明:以下想法不好不应在生产代码中使用。我假设您只是想要快速进行测试。

使用正则表达式来匹配标签。 Microsoft 在 CAtlRegExp 中提供了此功能。如果您使用的是 Visual Studio 2008 或更高版本,请在此处下载 ATL。然后,只需将 myString 提供给以下代码:

#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: 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文