2011-07-27 54 views
3

什麼是逃避任何std::wstring在正則表達式中使用的最佳方式?例如,將you owe me $轉換爲you owe me \$如何將字符串轉換爲正則表達式literal

我的場景:我想用std::tr1::wregex來搜索整個單詞。所以,我想要做的事,如:

std::wstring RegexEscape(const std::wstring& inp) 
{ 
    return ????? 
} 

bool ContainsWholeWord(const std::wstring& phrase, const std::wstring& word) 
{ 
    std::tr1::wregex regex(std::wstring(L"\\b") + RegexEscape(word) + L"\\b"); 
    return std::tr1::regex_match(phrase, regex); 
} 

回答

1

我不知道這是最聰明或最有效的,但我用 類似以下內容:

namespace { 
bool 
isMeta(char ch) 
{ 
    static bool const meta[UCHAR_MAX] = 
    { 
     // ... 
    }; 
    return meta[static_cast<unsigned char>(ch)]; 
} 

std::string 
sanitizeForRegEx(std::string const& original) 
{ 
    std::string result; 
    for (std::string::const_iterator iter = original.begin(); 
      iter != original.end(); 
      ++ iter) { 
     if (isMeta(*iter)) { 
      result += '\\'; 
     result += *iter; 
    } 
    return result; 
} 

對於wchar_t,我ð修改isMeta返回類似:

return ch >= 0 && ch < 128 && meta[ ch ]; 

meta初始化是有點孔,以及確切的VA 的提示取決於使用的正則表達式(或者如果使用了 boost::regex,則甚至可以使用這些選項)。

0

嗯,這很簡單!只需使用正則表達式即可!

std::wstring szTmp; // some string with $, (, ... 
std::wregex rgx_Meta(LR"(([\^\$\\\.\*\+\?\(\)\[\]\{\}\|]))"); 
std::wstring strEscaped(std::regex_replace(szTmp, rgx_Meta, LR"(\$1)")); 

這將用'\ $'替換'$'之類的所有特殊字符。

相關問題