【问题标题】:How can I use pattern matching in Postgres [duplicate]如何在 Postgres 中使用模式匹配 [重复]
【发布时间】:2020-11-16 05:50:02
【问题描述】:

我有一个这样的基本书籍表:

CREATE TABLE books (
  id integer primary key,
  name text not null
);
INSERT INTO books (id, name) VALUES (1, 'The Ghost');

我想搜索与搜索词 ^The Ghost$ 匹配的书名。如您所见,该术语中有一些正则表达式。如何通过正则表达式进行匹配?

我试过这样做,但没有结果

select *
from books
WHERE name like '%^The Ghost$%'

SQL 小提琴:http://sqlfiddle.com/#!17/8a5aa6/1

【问题讨论】:

    标签: sql regex postgresql select


    【解决方案1】:

    如果你的要求真的是逐字匹配^The Ghost$,那么你可以在这里使用相等比较:

    SELECT *
    FROM books
    WHERE name = 'The Ghost';
    

    如果您想使用正则表达式表达上述内容,您可以使用~ 运算符:

    SELECT *
    FROM books
    WHERE name ~ '^The Ghost$';
    

    【讨论】:

    • 可以使用~ 代替LIKE 来表示没有任何正则表达式的术语吗?它仍然能够匹配部分书名吗
    • 回答:也许吧。这取决于正则表达式/like 表达式。
    • name LIKE '%The Ghost%' 是否与name ~ 'The Ghost' 相同
    • 是的,在这种情况下,这两个表达式将匹配相同的内容。
    猜你喜欢
    • 2011-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多