使用MFC CString升级正则表达式搜索失败

时间:2010-09-20 08:22:35

标签: mfc cstring boost-regex

我在使用带有MFC CString的Boost正则表达式时遇到了问题。 正则表达式非常简单:它必须检查字符串是否以我正在寻找的dll的名称结尾。 在下面的代码CString路径DOES包含我正在寻找的DLL,但我不知道为什么正则表达式失败。 Uisng ReleaseBuffer增加缓冲区大小,因此Path of Path设置为MAX_PATH。 你知道为什么不正确吗? 我做了很多尝试,但总是失败。

#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 个答案:

答案 0 :(得分:1)

你的反斜杠需要加倍,因为C ++会吞掉第一个作为转义字符。尝试

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

此外,我认为您错误地使用了ReleaseBuffer。参数应该是返回的字符串的实际大小,否则字符串的结尾可能包含垃圾。如果您可以依赖于以null结尾的字符串,则可以始终使用-1作为参数,或者将其保留为默认值。