一.關鍵頭文件:
#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;
}