Home > Back-end >  how to match this line "04.08.2022 22:09" with regular expression in cpp
how to match this line "04.08.2022 22:09" with regular expression in cpp

Time:08-06

I want to match "04.08.2022 22:09" with regex in 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();
    }

CodePudding user response:

  • You need to use \d not /d to match digits.
  • You can also use \s to match one or more whitespaces instead of .* which matches zero or more of any character.
  • 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}.

CodePudding user response:

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}");

CodePudding user response:

The problem was in / instead of \. It works now.

  • Related