0

I'm compiling this with VS 2022 C++ compiler, as "ISO C++20 Standard (/std:c++20)" for a Debug configuration.

How come this throws the following std::regex_error:

regex_error(error_backref): The expression contained an invalid back reference.

std::wregex re;
bool bCaseSens = true;

re.assign(L"FilE", 
    std::wregex::ECMAScript | 
    std::wregex::nosubs |
    std::wregex::optimize |
    (bCaseSens ? 0 : std::wregex::icase)
);

but this compiles and works fine?

std::wregex re;
bool bCaseSens = true;

re.assign(L"FilE", 
    std::wregex::ECMAScript | 
    std::wregex::nosubs |
    std::wregex::optimize
);

PS. Note that the Release build doesn't throw that exception.

PS2. Also tried with older versions of C++ standard with the same effects.

3
  • In the first case, it's probably assign (4) because the 0 converts the expression to a std::size_t (or something convertible into that), but in the second case it's assign (3). q.v. en.cppreference.com/w/cpp/regex/basic_regex/assign.html Commented Oct 29 at 19:13
  • 1
    To add to the comment by @Eljay -- the type of the expression (bCaseSens ? 0 : std::wregex::icase) is int, not std::regex::syntax_option_type. That means that the type of the result of the sequence of | operators is also int, and not syntax_option_type, so the compiler picks an inappropriate overload of assign. Commented Oct 29 at 19:29
  • I've had bad luck using assign() on regex variables that haven't been initialized. It's better to do an initialize declaration std::wregex re(""); then re.assign() What I ended up adopting was to use a copy assign method, ex : typedef boost::wregex X_regex;\n #define MAKEREGEX(str,options) boost::wregex(str,options)\n X_regex re = MAKEREGEX( "\\bFilE\\b", ECMAScript | nosubs | optimize | (bCaseSens ? 0 : icase)); Commented Oct 30 at 18:36

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.