【问题标题】:std::regex escape "+" sign [duplicate]std::regex 转义“+”号 [重复]
【发布时间】: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"(\+)"

标签: c++ regex c++14


【解决方案1】:

您正在使用 C++ 字符串文字,其中 \ 是一个特殊字符,应该转义。所以你应该使用"\\+"

为避免双重转义,您还可以使用raw string literal,例如R"(\+)".

【讨论】:

    【解决方案2】:

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

        regex point("\\.");
    

    【讨论】:

      猜你喜欢
      • 2013-01-30
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2019-07-20
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      相关资源
      最近更新 更多