QRegularExpression中\-转义符生效原因咨询(含编译警告)
QRegularExpression Works Despite the Compilation Warning Let me break down this curious behavior for you, even though you’re seeing that "unknown escape sequence: '-'" warning:
1. How C++ Handles Unrecognized Escape Sequences
When you write \- in a C++ string literal, the compiler doesn’t recognize this as a valid escape sequence (valid ones are things like \n, \\, \t). Most mainstream compilers (GCC, Clang, MSVC) will flag this with a warning, but they’ll also silently drop the backslash and treat the sequence as a plain -.
So your original string:
"([а-я\-]+[бвгджзклмнпрстфхчцшщ])([еиоы][й]|[аия][я]|[иую][ю]|[еиоы][е]|[аоеиы][м][иу]|[ое][г][о]|(?<!ост)и?[аеиоыя]м|ост[а-яё]{1,3}|(?<!остиям)(?>и|ь.?)|[ао]в|н[аеио]|с[ая]|[ео][вк]|[иы]х|[ие]ну|[иуя]т|(?<![аеёиоуыэюя]{2})[аеёоуыэюя]+|и{2})$", QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption
Gets transformed by the compiler into:
"([а-я-]+[бвгджзклмнпрстфхчцшщ])([еиоы][й]|[аия][я]|[иую][ю]|[еиоы][е]|[аоеиы][м][иу]|[ое][г][о]|(?<!ост)и?[аеиоыя]м|ост[а-яё]{1,3}|(?<!остиям)(?>и|ь.?)|[ао]в|н[аеио]|с[ая]|[ео][вк]|[иы]х|[ие]ну|[иуя]т|(?<![аеёиоуыэюя]{2})[аеёоуыэюя]+|и{2})$", QRegularExpression::UseUnicodePropertiesOption | QRegularExpression::MultilineOption
before it’s passed to QRegularExpression.
2. How Regex Character Classes Treat -
In regular expression character classes ([]), the hyphen - only acts as a range separator (like a-z) when it’s placed between two characters. If you put it at the end (or the start) of the character class, it’s treated as a literal hyphen—no escape required.
That means [а-я-]+ in your regex correctly matches one or more Russian lowercase letters (а-я) or a hyphen -—exactly what you need to match hyphenated Russian words.
The Clean Fix to Eliminate the Warning
Even though your code works now, relying on this compiler-specific behavior isn’t ideal. To make your code portable and warning-free, you have two simple options:
- Move the hyphen to the start or end of the character class (no escape needed):
[а-я-]+or[-а-я]+ - Use a proper double backslash to escape the hyphen in the C++ string (so the regex engine sees
\-):[а-я\\-]+
Either approach will keep your regex functionality intact while getting rid of that annoying warning.
内容的提问来源于stack exchange,提问作者Eugene Anisiutkin

