1

I have a regex as:

std::regex regexp(
        R"(\$\ part,\ model.*[\n\r]([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*),([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*))",std::regex::extended);

The code compiles, but I receive the following error:

Unhandled exception at 0x748F49C2 in regex.exe: Microsoft C++ exception: std::regex_error at memory location 0x00EFEE30.
6
  • 1
    I suggest you remove std::regex::extended, use the default ECMAScript flavor. Commented Jan 25, 2021 at 12:53
  • But my string has multiple lines. a lot of "\n". Commented Jan 25, 2021 at 12:56
  • Regex flavor has nothing to do with the multiline input. Use the default one. Commented Jan 25, 2021 at 13:05
  • If you catch the exception, you will see regex_error(error_escape): The expression contained an invalid escaped character, or a trailing escape. Commented Jan 25, 2021 at 13:08
  • 2
    externded syntax only allows certain special characters to be escaped by a backslash, not any arbitrary character. In particular, space is not a special character, and \ is invalid in extended syntax. So are \n and \r it seems; those characters should be represented by themselves (which would be tricky in a raw string literal). All told, you probably don't want extended; you are probably looking for multiline option. Commented Jan 25, 2021 at 13:11

1 Answer 1

2

According to the regex spec, the effect of escaping a space (which is not a special character) is undefined:

9.4.2 ERE Ordinary Characters

... The interpretation of an ordinary character preceded by an unescaped <backslash> ( \ ) is undefined, except in the context of a bracket expression ...

Apparently in the MSVC implementation, std::regex_error gets thrown.

After fixing the escaping the regex compiles.

try {
    std::regex regexp(
        R"(\$ part, model.*[\n\r]([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*),([-]?[0-9]*\.?[0-9]+[Ee]?[-+]?[0-9]*))", std::regex::extended);
}
catch (std::exception const& e) {
    std::cerr << e.what() << std::endl;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.