Search code examples
regexqtbackslashqregexp

How to use QRegExp when there is only one bckslash?


I want to use QRegExp to detect Postgres like regular expressions. For QRegExp, doc says "To include a \ in a regexp, enter it twice, i.e. \"

Example: dollar amount:

\$[0-9]+.[0-9][0-9]

To successfully match this using QRegExp, it should be have two \\ like:

\\$[0-9]+.[0-9][0-9]

This was an example, but is there a way to make sure it always matches correctly? I was thinking replacing all \ with \\?

Thanks


Solution

  • Use the new improved QRegularExpression instead of QRegExp. It is much better than the old one in (almost) every regard.

    About your question: You can use QRegularExpression::escape() to do the replacements you talked about. However this is not useful for an entire pattern string, since it replaces all reserved characters. However it is useful for sub-strings you can use to assemble a pattern.

    Regarding your example... you simply need to take care of this manually. It is up to you to create valid patterns.

    And note that there is additional C/C++ escaping taking place. This means to create two backslashes "\\" in C/C++ you need aktucally 4 of them "\\\\".