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(); } }
常记溪亭日暮,沉醉不知归路。兴尽晚回舟,误入藕花深处。争渡,争渡,惊起一滩鸥鹭。
昨夜雨疏风骤,浓睡不消残酒。试问卷帘人,却道海棠依旧。知否?知否?应是绿肥红瘦。