2010-09-20 87 views
0

我在使用Boost正則表達式和MFC CString時遇到問題。 正則表達式非常簡單:它必須檢查字符串是否以我正在查找的dll的名稱結尾。 在下面的代碼CString路徑包含我正在尋找的DLL,但我不知道爲什麼正則表達式失敗。 Uisng ReleaseBuffer增加了緩衝區大小,所以Path of Path的長度被設置爲MAX_PATH。 你知道爲什麼不正確嗎? 我做了很多嘗試,但總是失敗。增強正則表達式搜索失敗,MFC CString

#include <boost/regex/mfc.hpp> 
const CString ValuesDLLName = _T("MyDll.dll"); 
boost::tregex EndsWithRegex(_T(".+MyDll.dll\s*$")); 

//boost::tregex EndsWithRegex1(_T("^.+Values\.dll\\s*$")); // not working 
//boost::tregex EndsWithRegex2(_T("^.+Values\.dll\s*$")); // not working 
//boost::tregex EndsWithRegex3(_T("^.+Values.dll\s*$")); // not working 
//boost::tregex EndsWithRegex4(_T("^.+Values.dll\\s*$")); // not working 
//boost::tregex EndsWithRegex5(_T("^.+Values\.dll\\s*$"),boost::regex::perl); // not working 
//boost::tregex EndsWithRegex6(_T("^.+Values\.dll\s*$"),boost::regex::perl); // not working 
//boost::tregex EndsWithRegex7(_T("^.+Values.dll\s*$"),boost::regex::perl); // not working 
//boost::tregex EndsWithRegex8(_T("^.+Values.dll\\s*$") ,boost::regex::perl); // not working 

CString Path; 
boost::tmatch What; 

_tsearchenv(ValuesDLLName, _T("PATH"), Path.GetBufferSetLength(260)); 
Path.ReleaseBuffer(260); 

bool endsWithDllName = boost::regex_search(Path, What, EndsWithRegex); 

回答

1

您的反斜槓需要翻倍,因爲C++會吞下第一個作爲轉義字符。嘗試

boost::tregex EndsWithRegex(_T("^.+Values\\.dll\\s*$")); 

另外我認爲你錯誤地使用了ReleaseBuffer。參數應該是返回的字符串的實際大小,否則字符串的末尾可能包含垃圾。如果您可以依賴於以空字符結尾的字符串,則始終可以使用-1作爲參數,或者將其保留爲缺省值,因爲它是缺省值。