兼容性 regexp_replace() postgres 和 h2

Compatibility regexp_replace() postgres and h2

我们在 Postgres

中有 Spring 引导应用程序和本机 sql
Select .... 
where regexp_replace(LOWER(company_name), '\s', '', 'g') = regexp_replace(LOWER(:suspect), '\s', '', 'g')

并测试了 H2 数据库,其中 regexp_replace flag 'g' 不受支持。

我不确定在 H2 的情况下是否需要 g 标志,因为所有匹配项的全局替换似乎是默认设置。来自 documentation:

Replaces each substring that matches a regular expression. For details, see the Java String.replaceAll() method. If any parameter is null (except optional flagsString parameter), the result is null.

我假设 H2 的 REGEXP_REPLACE 正在由 Java String#replaceAll 在幕后实施。在这种情况下,将自动替换所有匹配的子字符串。

关于你的两个不同数据库的问题,你真的应该尝试使用同一个数据库进行测试和生产。如果失败,您可能希望坚持使用 ANSI SQL。

注意,如果你想为 H2 添加一个缺失的函数,而你在其他数据库中有,你可以这样做。请注意,这不是本示例中提到的 regexp_replace,而是 regexp_match

的类似方法

这里是more info on how to include SQL like this and more info on H2 User Defined functions

# H2 DB - create regexp_match rough equivalent to Postgres
# note this does not do the true match
#
# include this in a file like so:
# src/test/resources/data.sql
CREATE ALIAS regexp_match AS '
    String getRegexpMatch(String input, String regex) {
       if (input == null){
        return null;
       };
       if (input.matches(regex)){
         return input;
       }
       return null;
    }
';