导读 这篇文章主要介绍了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判断字符串是否包含目标字符串的文章就介绍到这了。

原文来自:https://www.jb51.net/article/206167.htm

本文地址:https://www.linuxprobe.com/postgresql-linux-mean.html编辑:向金平,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/