PostgreSQL LIKE子句中的正则表达式 [英] Regular expression in PostgreSQL LIKE clause
问题描述
我坚持使用一个简单的正则表达式。不确定我缺少什么。正则表达式技巧有些生疏。
I'm stuck with a simple regular expression. Not sure what I'm missing. A little rusty on regex skills.
我要匹配的表达式是:
select * from table where value like '00[1-9]%'
-- (third character should not be 0)
因此,这应该与'0090D0DF143A'
(格式:文本)匹配,但不是!
So this should match '0090D0DF143A'
(format: text) but it's NOT!
推荐答案
像 @a_horse评论,您必须使用正则表达式运算符〜
使用方括号表达式。
还有更多内容。我建议:
Like @a_horse commented, you would have to use the regular expression operator ~
to use bracket expressions.
But there's more. I suggest:
SELECT *
FROM tbl
WHERE value ~ '^00[^0]'
^
...在开始时匹配字符串(您的原始表达式可以在 any 位置匹配)。
[^ 0]
...方括号表达式(字符类)匹配不是 0
的任何个字符。
^
... match at start of string (your original expression could match at any position).
[^0]
... a bracket expression (character class) matching any character that is not 0
.
或更好,但是:
SELECT *
FROM tbl
WHERE value LIKE '00%' -- starting with '00'
AND value NOT LIKE '000%' -- third character is not '0'
为什么? Like
没那么强大,但通常比正则表达式快。用便宜的 Like
表达式缩小候选集的范围可能快得多。
Why? LIKE
is not as powerful, but typically faster than regular expressions. It's probably substantially faster to narrow down the set of candidates with a cheap LIKE
expression.
通常,您会使用不喜欢'__0'
,但是由于我们已经在另一个谓词中建立了 Like '00%'
,因此我们可以使用较窄(便宜)的模式不喜欢'000'
。
Generally, you would use NOT LIKE '__0'
, but since we already establish LIKE '00%'
in the other predicate, we can use the narrower (cheaper) pattern NOT LIKE '000'
.
Postgres可以使用简单的btree 索引用于左锚表达式 value像'00%'
(对于大表而言很重要),而对于更复杂的正则表达式则可能不起作用。最新版本的Postgres可以将索引用于简单的正则表达式,因此可能可以在本示例中使用。详细信息:
Postgres can use a simple btree index for the left-anchored expressions value LIKE '00%'
(important for big tables), while that might not work for a more complex regular expression. The latest version of Postgres can use indexes for simple regular expressions, so it might work for this example. Details:
- Difference between LIKE and ~ in Postgres
这篇关于PostgreSQL LIKE子句中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!