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/