教你幾種PostgreSQL判斷字串是否包含目標字串的方法

大雄45發表於2021-03-12
導讀 這篇文章主要介紹了PostgreSQL判斷字串是否包含目標字串的多種方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑑價值,需要的朋友可以參考下

PostgreSQL判斷字串包含的幾種方法:

方式一: position(substring in string):

position(substring in string)函式:引數一:目標字串,引數二原字串,如果包含目標字串,會返回目標字串笫一次出現的位置,可以根據返回值是否大於0來判斷是否包含目標字串

select position('aa' in 'abcd');
 position 
----------
    0
select position('ab' in 'abcd');
 position 
----------
    1
select position('ab' in 'abcdab');
 position 
----------
    1
方式二: strpos(string, substring)

strpos(string, substring)函式:引數一:原字串,目標字串,宣告子串的位置,作用與position函式一致。

select position('abcd','aa');
 position 
----------
    0
 
select position('abcd','ab');
 position 
----------
    1
 
select position('abcdab','ab');
 position 
----------
    1
方式三:使用正規表示式

如果包含目標字串返回t,不包含返回f

select 'abcd' ~ 'aa' as result;
result
------
  f 
    
select 'abcd' ~ 'ab' as result;
result
------
  t 
    
select 'abcdab' ~ 'ab' as result;
result
------
  t
方式四:使用陣列的@>運算子(不能準確判斷是否包含)
select regexp_split_to_array('abcd','') @> array['b','e'] as result;
result
------
 f
 
select regexp_split_to_array('abcd','') @> array['a','b'] as result;
result
------
 t

注意下面這些例子:

select regexp_split_to_array('abcd','') @> array['a','a'] as result;
result
----------
 t
 
select regexp_split_to_array('abcd','') @> array['a','c'] as result;
result
----------
 t
 
select regexp_split_to_array('abcd','') @> array['a','c','a','c'] as result;
result
----------
 t

可以看出,陣列的包含運算子判斷的時候不管順序、重複,只要包含了就返回true,在真正使用的時候注意。

到此這篇關於PostgreSQL判斷字串是否包含目標字串的文章就介紹到這了。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2762454/,如需轉載,請註明出處,否則將追究法律責任。

相關文章