VC++中使用正则表达式RegExp

使用vbscript中的正则表达式

复制一份 C:\Windows\System32\vbscript.dll ,使用VC++以资源的方式打开VBScript.dll,在其中选择TypeLib,将第2个TypeLib输出为 vbRegExp.tlb,   将它放入工程目录(xxx.vcxproj所在目录)

1.

 

 2.

 

3.

 

 

 4.

导出文件,命名为 vbRegExp.tlb

OK   3.42KB

 

 使用:

在 stdafx.h 的最后添加    #import "vbRegExp.tlb" no_namespace

void testRegEx()
{
    CoInitialize(NULL);
    {
        IRegExpPtr regExpPtr(__uuidof(RegExp));
        regExpPtr->PutGlobal(VARIANT_TRUE);
        regExpPtr->PutPattern("\\d+[A-z]{1,2}");
        _bstr_t testStr = "This 0  1dd2d345";
        IMatchCollectionPtr matches = regExpPtr->Execute(testStr);

        long count = matches->GetCount(); 
        for (long i = 0; i<count; i++)
        {
            IMatchPtr match = matches->GetItem(i);
            if (match)
            {
                CStringA str = (char*)match->GetValue();
            }
        }
    }
    CoUninitialize();
}

//或者
class Bootstrapper
{
    BOOL m_bComInitialized;
public:
    Bootstrapper(){
        m_bComInitialized = FALSE;
        if (SUCCEEDED(::CoInitialize(NULL)))
            m_bComInitialized = TRUE;
    }
    ~Bootstrapper(){
        if (m_bComInitialized)
            ::CoUninitialize();
    }
};
void testRegEx()
{
    Bootstrapper bst;
    try{
        IRegExpPtr regExpPtr(__uuidof(RegExp));
        regExpPtr->PutGlobal(VARIANT_TRUE);
        regExpPtr->PutPattern("\\d+[A-z]{1,2}");
        _bstr_t testStr = "This 0  1dd2d345";
        IMatchCollectionPtr matches = regExpPtr->Execute(testStr);

        long count = matches->GetCount();
        for (long i = 0; i<count; i++)
        {
            IMatchPtr match = matches->GetItem(i);
            if (match)
            {
                CStringA str = (char*)match->GetValue();
            }
        }
    }
    catch (_com_error &e){
        _bstr_t err = e.Description();
    }
}
View Code

 

posted @ 2020-06-13 09:57  htj10  阅读(543)  评论(0编辑  收藏  举报
TOP