How to convert regex Pattern from C# to C++?

Asked

Viewed 41 times

4

I’m trying to use C++ regex but I’m having some difficulties, one of them is that Pattern was in a C#code, and I know practically nothing of regex in C++, and so the code does not work as it should in C++

Here’s the excerpt of the code that doesn’t work as it should:

if (!std::regex_match("BLUS31029", std::regex("^B[LC][JUEAK][SM]\d{5}$")))
    print_error("Invalid game id: " + game_id);
else
    ::id_ = game_id;
}

PS: I already changed the regex_match for regex_search and yet it didn’t work

  • "does not work" means that some error appears when compiling the program, or the result is not expected? Which compiler you are using?

  • @Gomiero It doesn’t work in the sense of giving the expected result q in the case is true, and I’m using Visual Studio 2019

1 answer

4


In the string of the regular expression, the character \d is recognized by the compiler so incorrect as a exhaust (escape sequence).

In several languages, the backslash \ followed by a symbol, is used to represent characters other than may be printed or have special meanings.

Example: \n represents the action "New Line".

To represent the backslash character, it is necessary to use two bars \\, to indicate to the compiler that it is not a escape sequence.

Depending on the configuration of Visual Studio (2019), during compilation, it must have issued a warning stating a sequence not recognized:

Warning C4129: ’d': unrecognized Character escape

The excerpt from the program in the question, with the corrected regular expression, is as follows::

if (!std::regex_match("BLUS31029", std::regex("^B[LC][JUEAK][SM]\\d{5}$")))
    print_error("Invalid game id: " + game_id);
else
    ::id_ = game_id;
}
  • The problem is in the string itself, not in Pattern, I discovered this dps, the string I put in regex has something wrong that makes the match result false, with Pattern is all right

Browser other questions tagged

You are not signed in. Login or sign up in order to post.