【问题标题】:How to use regexp in where clause to filter rows in Postgres?如何在 where 子句中使用正则表达式来过滤 Postgres 中的行?
【发布时间】:2020-09-20 09:00:07
【问题描述】:

我在 postgres 11.0 中有下表

col1 col2 col3 col4
NCT00001723 4894402 xenical (orlistat)capsules xenical
NCT00001724 4894403 xenical (orlistat)capsules orlistat
NCT00001725 4894404 capsules capsules
NCT00001726 4894405 insulin ins

我想过滤以上行,以便 col3 = col4 或 col3 的确切内容应包含在 col4 中。

想要的输出是:

col1 col2 col3 col4
NCT00001723 4894402 xenical (orlistat)capsules xenical
NCT00001724 4894403 xenical (orlistat)capsules orlistat
NCT00001725 4894404 capsules capsules

我正在尝试下面的查询来获得这个输出。

SELECT
    *
FROM
    table 
where col3 = col4 or                         --exact match
regexp_matches(col3, '(.*).*\(') = col4 or   --match content before brackets
regexp_matches(col3, '.*\(.*\).*') = col4 --match content in brackets

这里的任何建议都会很有帮助。谢谢

【问题讨论】:

    标签: sql regex postgresql select where-clause


    【解决方案1】:

    如果我没听错的话,你可以直接使用word boundaries escape \y

    \y:仅匹配单词的开头或结尾

    在您的查询中:

    select * from mytable where col3 ~  ('\y' || col4 || '\y')
    

    Demo on DB Fiddle

    col1 col2 col3 col4
    NCT00001723 4894402 xenical (orlistat)capsules xenical
    NCT00001724 4894403 xenical (orlistat)capsules orlistat
    NCT00001725 4894404 capsules capsules

    【讨论】:

    • 每当我使用它时,我都会收到此错误“[代码:0,SQL 状态:2201B] 错误:无效的正则表达式:量词操作数无效”这是什么意思?
    • @rshar 这意味着您的 col4 包含一些值(不是您显示的值),这些值具有对正则表达式引擎有意义的字符。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2015-07-26
    • 1970-01-01
    相关资源
    最近更新 更多