首页 > 解决方案 > 在 where 子句中的 Postgres 正则表达式

问题描述

postgres 中是否有匹配的解决方案,如下例所示:

“测试”表条目:

id |                            url                             
----+-------------------------------------------------------------
 1  | /services/system
 2  | /services/system/{uuid}/group
 3  | /services/system/{uuid}/group/{uuid}/port

我想将以下输入字符串与表中存在的 url 列进行匹配:

1. /services/system/1/group          --> should match row 3
2. /services/system/1/group/2/port   --> should match row 3
3. /services/system/1/group          --> should match row 2
4. /services/system/1/group/2        --> should not match
5. /services/system/1                --> should not match

我尝试了以下查询来匹配第 3 行,但它不起作用:

select * from test where regexp_replace(url, '{uuid}', '*', 'g') ~ '/services/system/1/group/1/port'

有什么解决办法吗?

标签: sqlregexpostgresql

解决方案


考虑到您在问题和评论中给出的场景,您可以使用以下查询:

select * from test 
where '/services/system/1/group' ~ concat('^',replace(url,'{uuid}','[^/]+'),'$')

在这里它将检查除/代替之外的任何字符{uuid}

编辑 如果你只想要字母数字,那么你应该使用试试这个:

select * from test 
where '/services/system/1/group' ~ concat('^',replace(url,'{uuid}','[\w]+'),'$')

演示


推荐阅读