C++正则表达式转义标点字符,如"."
C++ regex escaping punctional characters like "."
将字符串中的"."与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")
相关文章:
- 带有多个字符分隔符的正则表达式
- C++ [正则表达式] 如何提取给定的字符值
- C++正则表达式字符类不匹配
- 通过正则表达式拆分字符串会切断结果的第一个字母
- 正则表达式 - 匹配不遵循特定模式的字符
- 使用具有特殊字符的正则表达式标记 C++ 字符串
- 正则表达式:从模式字符串 1.string2'string3 中提取字符串,其中字符串 1 可以包含 '." 字符
- 提升正则表达式 cpp 用于查找 %% 之间的字符串,输出不包括 % 字符本身
- 如何使用正则表达式匹配不包含特殊字符(&、\、<、>、|、)的字符串,除非它们以反斜杠开头
- 将一个特定字符替换为正则表达式匹配中的另一个字符
- 修改正则表达式以包含反斜杠和单引号(以便反斜杠表现为转义字符)
- C++正则表达式中的特殊字符
- 使用正则表达式为每个连续的大写字符附加'.'
- C++正则表达式转义标点字符,如"."
- 正则表达式.查找所有带有非拉丁字符的单词
- 如何构造一个前面没有特定字符的正则表达式
- 正则表达式中的成对字符
- 如何在 C/C++ PCRE 正则表达式中使用 UTF-8 文字字符
- 正则表达式:捕获不带前导字符的字符串
- 正则表达式:仅限数字 + 字母数字 + 特殊字符