ATL正则表达式库使用

一.关键头文件:
#include <atlrx.h>
vs2005自带.

VS 2008中由于将ALT项目的部分代码剥离出去成为了独立的开源项目,需要用到ALT中正则表达式等功能就需要手动下载。
参考:http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=306398
下载地址:http://www.codeplex.com/AtlServer
把下载的东西解压缩到一个目录,比如c:\alt\
在VS里面[工具]--[选项]--[项目和解决方案]--[VC++目录],在右上角选择[包含引用的文件]中加入c:\alt\include就OK了

二.
关于
CAtlRegExp 及 GRETA      
不支持   {m,n} 这样的限定符
而Boost支持

三.
还有一个值得注意的地方就是ATL中用大括号({})表示其子匹配
子匹配Group从0开始.

四.关键类及结构体:
1、 CATLRegExp类
声明:
template <class CharTraits=CAtlRECharTraits>
class CAtlRegExp;
2、 CAtlREMatchContext类
声明:
template <class CharTraits=CAtlRECharTraits>
class CAtlREMatchContext
3.
CAtlREMatchContext<>::MatchGroup

//代码1:这里请注意只用代码环境为多字符集,非UNICODE.
#include <iostream>
#include <afxwin.h>
#include <atlrx.h>
using namespace std;

int main(int argc, char* argv[]) {
    CAtlRegExp<> re;
    CAtlREMatchContext<> mc;

    const char* szIn = "98a76";
    char szMatch[128];
    memset(szMatch,'\0',128);
    re.Parse("[0-9][0-9]");
    while(re.Match(szIn,&mc,&szIn)){
        strncpy(szMatch,mc.m_Match.szStart, mc.m_Match.szEnd-mc.m_Match.szStart );
        cout << szMatch << endl;
    }
    return 0;
}


/*
项目中,代码我是这样写的.
        CString strMatch;
#ifdef _UNICODE
        wcsncpy(strMatch.GetBuffer(mg.szEnd-mg.szStart),mg.szStart,mg.szEnd - mg.szStart);
#else
        strncpy(strMatch.GetBuffer(mg.szEnd-mg.szStart),mg.szStart,mg.szEnd - mg.szStart);
#endif
        strMatch.ReleaseBuffer();
*/




用个MSDN上的代码:
http://msdn.microsoft.com/zh-cn/library/k3zs4axe(VS.80).aspx 
请注意子匹配Group 及CAtlREMatchContext<>类GetMatch()方法的使用. 
其他就不详细讲述了.
// catlregexp_class.cpp
#include <afx.h>
#include <atlrx.h>

int main(int argc, char* argv[])
{
    CAtlRegExp<> reUrl;
    // Five match groups: scheme, authority, path, query, fragment
    REParseError status = reUrl.Parse(
        "({[^:/?#]+}:)?(//{[^/?#]*})?{[^?#]*}(?{[^#]*})?(#{.*})?" );

    if (REPARSE_ERROR_OK != status)
    {
        // Unexpected error.
        return 0;
    }

    CAtlREMatchContext<> mcUrl;
    if (!reUrl.Match(
"http://search.microsoft.com/us/Search.asp?qu=atl&boolean=ALL#results",
        &mcUrl))
    {
        // Unexpected error.
        return 0;
    }

    for (UINT nGroupIndex = 0; nGroupIndex < mcUrl.m_uNumGroups;
         ++nGroupIndex)
    {
        const CAtlREMatchContext<>::RECHAR* szStart = 0;
        const CAtlREMatchContext<>::RECHAR* szEnd = 0;
        mcUrl.GetMatch(nGroupIndex, &szStart, &szEnd);

        ptrdiff_t nLength = szEnd - szStart;
        printf_s("%d: \"%.*s\"\n", nGroupIndex, nLength, szStart);
    }

    return 0;
}

posted @ 2011-01-27 02:35  alex618  阅读(1462)  评论(0编辑  收藏  举报