具有相同通配符的模式匹配

Pattern matching with identical wildcards

我正在使用 PostgreSQL,想知道您是否可以让通配符保留其值。

比如说我有

select * from tableOne where field like ‘_DEF_’;

有没有办法让第一个和最后一个通配符成为完全相同的字符?

因此,示例匹配结果可能是:ADEFA 或 ZDEFZ。

您可以使用带反向引用的正则表达式:

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

^(.)DEF()$ 表示:开头的某个字符后跟 DEF 后跟第一个字符必须出现在字符串的末尾。

()定义一个组,引用第一个组(在本例中是输入序列中的第一个字符)

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

使用正则表达式:

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

输出:

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