std::正则表达式转义"+"符号

std::regex escape "+" sign

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

我不明白如何使用正则表达式单词进行转义。 我尝试检测"+"。我知道这也是正则表达式的一个特殊标志,表明后面有一个或多个标志。

据我了解,这些特殊符号需要用"\"转义。对于 +,这似乎适用于"." 但是,如果我用"+ "转义加号,我会得到运行时异常。

"匹配。regex_error(error_badrepeat): 前面没有 *?+{ 中的一个 通过有效的 reguar 表达式。

所以我假设它没有正确转义。

例:

#include <iostream>
#include <string>
#include <regex>
#include <exception>

int main() 
try {
std::regex point(".");
std::string s1 = ".";
if (std::regex_match(s1, point))
std::cout << "matched" << s1;
std::regex plus("+");
std::string s2 = "+";
if (std::regex_match(s2, plus))
std::cout << "matched" << s2;
char c;
std::cin >> c;
}
catch (std::runtime_error& e) {
std::cerr << e.what()<<'n';
char c;
std::cin >> c;
}
catch (...) {
std::cerr << "unknown errorn";
char c;
std::cin >> c;
}

您使用的是C++字符串文本,其中是一个特殊字符,应进行转义。所以你应该使用"\+".

为了避免双重转义,您还可以使用原始字符串文字,例如R"(+)".

DOT.,加上符号+是C++中正则表达式操作的特殊字符。所以你必须像下面这样做:-

regex point("\.");