C++正则表达式转义标点字符,如"."

C++ regex escaping punctional characters like "."

本文关键字:字符 正则表达式 转义 C++      更新时间:2023-10-16

将字符串中的"."与std::tr1::regex类匹配使我使用了一种奇怪的解决方法。

为什么我需要检查"\\\\."而不是"\\."?

regex(".") // Matches everything (but "n") as expected.
regex("\.") // Matches everything (but "n").
regex("\\.") // Matches only ".".

有人可以解释我为什么吗?这真的很困扰我,因为我使用不需要这种语法的boost::regex类编写了代码。

编辑:对不起,regex("\\.")似乎什么都不匹配。

编辑2:一些代码

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 = "";
}
这是因为

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

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

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

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

解决方案是改用match_continuous

尝试通过其 ASCII 代码对点进行转义:

regex("\x2E")