PostgreSQL: 如何判断字符串中是否包含指定字符。
今天有开发人员问到: PostgreSQL 中是否有函数可以判断一个字符串中是否包含指定字符,如果包
含则返回 ture ,否则返回 false,例如,如果字符串 'abcde' 中包含 'ab' 则返回 true,于是想了想,共总
结以下三种方法,暂且不考虑性能。
一 方法一: 使用 position 函数
--1.1 使用 position 函数
SELECT position('aa' in 'kkjaadsd');
SELECT position('aa' in 'aadsd');
--1.2 position 函数简价
Function: position(substring in string)
Return Type: int
Description: Location of specified substring
备注: position 函数是找出一个字符串在另一个字符串中出现的位置,如果找不到则返回整型 0。
二 方法二:使用正责表达式
--2.1 使用正责表达式
SELECT 'aa' ~ 'kkjaadsd';
SELECT 'kkjaadsd' ~ 'aa';
备注:上面使用的是正责表达式,关于正责表达式的更多用法,请参考手册
http://www.postgresql.org/docs/9.2/static/functions-matching.html
也可以参考之前的 blog
http://francs3.blog.163.com/blog/static/4057672720112221400871/
三 方法三:使用矩阵比较函数 @>
--3.1 使用矩阵比较函数 @>
SELECT regexp_split_to_array('kkjaadsd','') @> array['a','a'];
备注:方法三使用了字符串函数 regexp_split_to_array 和矩阵操作符 @>
--3.2 regexp_split_to_array 函数简介
regexp_split_to_array 函数用于将字符串转换成矩阵,用户如下
Function: regexp_split_to_array(string text, pattern text [, flags text ])
Return Type: text[]
Description: Split string using a POSIX regular expression as the delimiter. See Section 9.7.3 for more information.
--3.3 example
select regexp_split_to_array('hello world',' ');
select regexp_split_to_array('hello','');
--3.4 矩阵 @> 操作符简介
Operator: @>
Description: contains
Example: ARRAY[1,4,3] @> ARRAY[3,1]
Result: t
--3.5 example
注:后面的矩阵数组如果是前面的子集则返回t,否则返回f
SELECT regexp_split_to_array('kkjaadsd','') @> array['aa'];
SELECT regexp_split_to_array('kkj aa dsd',' ') @> array['aa'];
SELECT regexp_split_to_array('kkj aa dsd',' ') @> array['a','a'];
备注:@> 操作符是用来比较矩阵数据是否包含,关于矩阵操作符和函数,参考手册
http://www.postgresql.org/docs/9.2/static/functions-array.html。
参考:http://francs3.blog.163.com/blog/static/40576727201262615549532/