Pattern matching with identical wildcards

帅比萌擦擦* 提交于 2019-12-10 20:42:24

问题


I'm working with PostgreSQL and want to know whether you can have a wildcard retain its value.

So for example say I had

select * from tableOne where field like ‘_DEF_’;

Is there a way to get the first and last wildcard to be the exact same character?

So an example matching result could be: ADEFA or ZDEFZ.


回答1:


You can use a regular expression with a back-reference:

select * 
from some_table
where some_column ~* '^(.)DEF(\1)$'

^(.)DEF(\1)$ means: some character at the beginning followed DEF followed by the first character must occur at the end of the string.

The () defines a group and the \1 references the first group (which is the first character in the input sequence in this example)

SQLFiddle example: http://sqlfiddle.com/#!15/d4c4d/1




回答2:


Use regular expression:

with test as (
    select 'xABa' as foo
    union select 'xABx'
    union select 'xJBx'
)
select * from test
where foo ~* E'^(.)AB\\1$'

Outputs:

 foo  
------
 xABx
(1 row)


来源:https://stackoverflow.com/questions/29033022/pattern-matching-with-identical-wildcards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!