Postgresql Regex - escape possessive quantifiers [closed]
-
10-03-2021 - |
Question
I have a query that is formed in Java
SELECT * from COMPONENTS WHERE name ~* = 'searchTerm';
This query hits PostgreSQL via JDBC and returns the results. I have to use ~*
because the user from the UI may search for the entries using a regex. (The user itself passes the regex from the UI and all security has been taken care of to prevent SQL-injection).
It all worked fine until the user searched for just C++
. PostgreSQL returned with an error:
ERROR: invalid regular expression: quantifier operand invalid
Upon reading many articles, I understood the
at +
is acting like a possessive quantifier and that PostgreSQL doesn't support it. Is there a way I can escape such characters from the input string or is there a better way to move forward?
Solution
Don't let the user enter regular expressions. A carefully crafted regular expression can hog the CPU forever.
If all you want to do is looking for substrings in a case insensitive fashion, use ILIKE
:
WHERE name ILIKE '%C++%'