C++正则表达式转义像"."这样的函数字符.

Tim*_*Tim 3 c++ regex escaping

匹配"." 在std::tr1::regex类的字符串中使我使用一个奇怪的解决方法.

为什么我需要检查"\\\\".代替 "\\."?

regex(".") // Matches everything (but "\n") as expected.
regex("\\.") // Matches everything (but "\n").
regex("\\\\.") // Matches only ".".
Run Code Online (Sandbox Code Playgroud)

有人能解释一下为什么吗?因为我使用boost::regex类编写代码而不需要这种语法,所以真的很烦我.

编辑:对不起,regex("\\\\.")好像什么都不匹配.

Edit2:一些代码

void parser::lex(regex& token)
{
    // Skipping whitespaces
    {
        regex ws("\\s*");
        sregex_token_iterator wit(source.begin() + pos, source.end(), ws, regex_constants::match_default), wend;
        if(wit != wend)
            pos += (*wit).length();
    }

    sregex_token_iterator it(source.begin() + pos, source.end(), token, regex_constants::match_default), end;
    if (it != end)
        temp = *it;
    else
        temp = "";
}
Run Code Online (Sandbox Code Playgroud)

Age*_*ien 8

这是因为\.被解释为转义序列,语言本身试图将其解释为单个字符.你想要的是你的正则表达式包含实际的字符串"\.",这是\\.因为\\是反斜杠字符(\)的转义序列而写的.


Age*_*ien 2

事实证明,实际问题是由于sregex_token_iterator使用的方式造成的。使用match_default意味着它总是在字符串中查找下一个匹配项(如果有),即使中间存在不匹配项。那是,

string source = "AAA.BBB";
regex dot("\\.");
sregex_token_iterator wit(source.begin(), source.end(), dot, regex_constants::match_default);
Run Code Online (Sandbox Code Playgroud)

会在点处给出匹配,而不是报告没有匹配。

解决办法就是使用match_continuous代替。