简体   繁体   English

如何将这一行“04.08.2022 22:09”与cpp中的正则表达式匹配

[英]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();
    }
  • You need to use \d not /d to match digits.您需要使用\d而不是/d来匹配数字。
  • You can also use \s+ to match one or more whitespaces instead of .* which matches zero or more of any character.您还可以使用\s+匹配一个或多个空格,而不是.*匹配零个或多个任意字符。
  • You should also escape the .您还应该逃避. characters that you want to match to not make it match any character.您要匹配的字符以使其不匹配任何字符。
  • I also recommend using raw string literals when creating string literals with a lot of backslashes.我还建议在创建带有大量反斜杠的字符串文字时使用原始字符串文字。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM