简体   繁体   中英

JPQL substring with regex

I have a table folder with rows like

id  |  path
1   | root
2   | root.first
3   | root.second
4   | root.first.child1
5   | root.first.child1.grandchild1
6   | root.first.child2

I have to fetch only the rows with path root.first.child1 and root.first.child2 but not root.first.child1.grandchild1 I can achieve this as native query with substring like

select path from folder 
where substring (path from '((root.first\.)[^\.]+)?') is not null;

I am looking for an equivalent query in JPQL. substring in JPQL seems to be with index and a length but I couldn't get reference as to whether it can be used with regex pattern.

There seems to be no universal solution, however you can create a polyfill function in Postgres which will allow you to use POSIX regex on both servers.

CREATE OR REPLACE FUNCTION REGEXP_LIKE (IN input text, IN pattern text, IN flags varchar DEFAULT '')
RETURNS BOOLEAN
IMMUTABLE
COST 0.013
AS $$
BEGIN
    RETURN array_length(regexp_matches(input, pattern, flags), 1) > 0;
END;
$$ LANGUAGE plpgsql;

The cost is a rough measurement with real data.

With this you can use REGEXP_LIKE in both Oracle and PostgreSQL almost identically. c , i and m seem to be the only flags they both agree how they should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM