如何将字符串转换为正则表达式文字

时间:2011-07-27 14:57:39

标签: c++ regex tr1

在正则表达式中使用任意std::wstring的最佳方法是什么?例如,将you owe me $转换为you owe me \$

我的方案:我想使用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);
}

2 个答案:

答案 0 :(得分: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的初始化有点蠢,而且确切的值 取决于使用的正则表达式(甚至是if 使用了boost::regex

答案 1 :(得分:0)

嗯,这很简单!只需使用正则表达式即可!

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

这将取代所有特殊字符,例如&#39; $&#39;与&#39; \ $&#39;。

相关问题