[英]how to match this line "04.08.2022 22:09" with regular expression in cpp
I want to match "04.08.2022 22:09" with regex in c++.我想将“04.08.2022 22:09”与 c++ 中的正则表达式匹配。 The code below doesn't work (doesn't match).
下面的代码不起作用(不匹配)。
//04.08.2022 22:09
if (std::regex_match(line, std::regex("^/d{2}./d{2}./d{4}.*/d/d:/d/d.*")))
{
cout << line << "\n";
cin.get();
}
\d
not /d
to match digits.\d
而不是/d
来匹配数字。\s+
to match one or more whitespaces instead of .*
which matches zero or more of any character.\s+
匹配一个或多个空格,而不是.*
匹配零个或多个任意字符。.
.
characters that you want to match to not make it match any character. Example:例子:
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string line = "04.08.2022 22:09";
std::regex re(R"aw(^\d{2}\.\d{2}\.\d{4}\s+\d{2}:\d{2})aw");
if (std::regex_match(line, re)) {
std::cout << line << '\n';
}
}
If the one-digit hours are not prepended with 0
, you need to match the hour with \d{1,2}
instead of \d{2}
.如果一位数的小时数未以
0
开头,则需要将小时数与\d{1,2}
而不是\d{2}
匹配。
I don't what is the issue behind it you should explain it and also make sure if you trying to match the date format.我不知道它背后的问题是什么,您应该对其进行解释,并确保您是否尝试匹配日期格式。 One simple solution would be:
一个简单的解决方案是:
std::regex r("\\d{2}\\.\\d{2}\\.\\d{4} \\d{2}:\\d{2}");
The problem was in / instead of \.问题出在 / 而不是 \。 It works now.
现在可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.