【发布时间】:2018-03-12 17:30:26
【问题描述】:
我不明白如何用正则表达式转义。 我尝试检测“+”。我知道这也是正则表达式的一个特殊符号,表示后面有一个或多个符号。
据我了解,这些特殊符号需要用“\”转义。对于 + 这似乎与“。”一起使用。但是,如果我用 "+ 转义一个加号,我会得到一个运行时异常。
"matched.regex_error(error_badrepeat): *?+{ 之一不在前面 通过有效的正则表达式。”
所以我认为它没有正确转义。
例子:
#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 error\n";
char c;
std::cin >> c;
}
【问题讨论】:
-
转义\,这样你的字符串中就有了。它给出了 \\+.
-
或者使用原始字符串,
r"(\+)"