LIKE以数字结尾的匹配字符串

时间:2013-06-26 23:34:35

标签: sql postgresql pattern-matching sql-like

我有一个包含资源路径的列,如下所示:

/apiv3/widgets/100
/apiv3/widgets/search
/apiv3/widgets/new

我正在尝试获得LIKE或REG_EX,只会匹配以数字结尾的字符串

我尝试了一些事情,例如:

LIKE '\/apiv3\/widgets\/[0-9]%'
LIKE '\/apiv3\/widgets\/[^0-9]%'

如何匹配仅以任意长度的数值结尾的路径?

2 个答案:

答案 0 :(得分:10)

使用正则表达式匹配(~ 对于以数字结尾的字符串:

...
WHERE value ~ '\d$'

\d .. "digit" class shorthand
$ .. matches at the end of a string

E'\d$'不正确。这 escape string 对于在最后/之后以数字结尾的字符串:

...
WHERE value ~ '/\d+$'

+ ..一个或多个原子
/ .. literal /

快速测试:

SELECT x, x ~ '\d$' As one,  x ~ '/\d+$' As two
FROM  (
    VALUES
     ('/apiv3/widgets/100')
    ,('/apiv3/widgets/search')
    ,('/apiv3/widgets/new')
    ,('/apiv3/widgets/added_test17')
    ) AS t(x);

              x              | one | two
-----------------------------+-----+-----
 /apiv3/widgets/100          | t   | t
 /apiv3/widgets/search       | f   | f
 /apiv3/widgets/new          | f   | f
 /apiv3/widgets/added_test17 | t   | f

答案 1 :(得分:0)

请参阅第9.7.2节,了解' SIMILAR'常用表达。 LIKE不支持他们。

http://www.postgresql.org/docs/current/static/functions-matching.html

示例:

'abc' SIMILAR TO 'abc'      true
'abc' SIMILAR TO 'a'        false
'abc' SIMILAR TO '%(b|d)%'  true
'abc' SIMILAR TO '(b|c)%'   false