我四处搜索,但仍然找不到错误。
为什么下面的代码打印出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/