L
L
Ler Den2019-01-03 22:26:28
PostgreSQL
Ler Den, 2019-01-03 22:26:28

Why does the error "invalid regular expression: quantifier operand invalid" occur?

Hello. There is a filter table for books.

create table filter
(
  "id" serial PRIMARY KEY,
  "user_id" serial REFERENCES public.user (id) ON DELETE CASCADE,
  "keywords" text []
);

When a new book is added to the database, it searches for existing filters and keywords in them to notify the user of a new entry.
Adding a book. Used by pg-promise
self.create = function (obj) {
        return db.query(`INSERT INTO public.filter (user_id, keywords) 
        VALUES ($(userId), $(keywords)) RETURNING id;`, obj);
};

Keyword search looks something like this. We get a string (a piece of text) as input
SELECT * FROM public.filter WHERE
LOWER('Some long string from a book') ~ ANY(public.filter.keywords);

And if the keyword contains some special character in the filter, for example (c++), then an error occurs
ERROR:  ОШИБКА:  неверное регулярное выражение: quantifier operand invalid

SQL state: 2201B

Why so?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaliy Orlov, 2019-01-03
@orlov0562

Try escaping special characters (pluses in the word "c++")
To use a literal instance of a special character in a regular expression, precede it by two backslash (\) characters. The MySQL parser interprets one of the backslashes, and the regular expression library interprets the other. For example, to match the string 1+2 that contains the special + character, only the last of the following regular expressions is the correct one:

mysql> SELECT REGEXP_LIKE('1+2', '1+2');                       -> 0
mysql> SELECT REGEXP_LIKE('1+2', '1\+2');                      -> 0
mysql> SELECT REGEXP_LIKE('1+2', '1\\+2');                     -> 1

in postgre I think the same

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question