c++ - std::regex 未按预期工作

标签 c++ regex

我四处搜索,但仍然找不到错误。

为什么下面的代码打印出false,我期望是true

#include <iostream>
#include <regex>

using namespace std;

int main()
{
    std::string in("15\n");
    std::regex r("[1-9]+[0-9]*\\n",
                 std::regex_constants::extended);

    std::cout << std::boolalpha;
    std::cout << std::regex_match(in, r) << std::endl;
}

未给出使用 regex_search 的选项。

最佳答案

正则表达式中的“\n”之前有一个额外的斜杠。代码打印出 true,只是删除了斜杠。

#include <iostream>
#include <regex>

using namespace std;

int main()
{
    std::string in("15\n");
    std::regex r("[1-9]+[0-9]*\n",
                 std::regex_constants::extended);

    std::cout << std::boolalpha;
    std::cout << std::regex_match(in, r) << std::endl;
}

编辑:@rici 在评论中解释了为什么这是一个问题:

Posix-standard extended regular expressions (selected with std::regex_constants::extended) do not recognize C-escape sequences such as \n. See Posix base definitions 9.4.2: "The interpretation of an ordinary character preceded by a ( '\' ) is undefined."

关于c++ - std::regex 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27908903/

相关文章:

c++ - Matlab 与 C++ 之间的 TCP/IP 通信

c++ - 三角形 : Determine if an array includes a triangular triplet (Codility)

java - 将字符串中的文本替换为异常

javascript - 在正则表达式中允许点 (.)

c++ - GLEW给出了许多错误信息

c++ - 未定义对链接库中 SDL2 函数的引用 (Code::Blocks)

c++ - 读取字符串直到行尾

javascript - 验证函数不应接受字母字符

Python 正则表达式 : find "com" or "org"

Java : String. 匹配()