第一次出现字符后剪切字符串 [英] Cut string after first occurrence of a character
问题描述
我有类似'keepme:cutme'或'string-with-with-separator'之类的字符串,应分别成为'keepme'和'string-without-separator'。可以在PostgreSQL中完成吗?我试过了:
I have strings like 'keepme:cutme' or 'string-without-separator' which should become respectively 'keepme' and 'string-without-separator'. Can this be done in PostgreSQL? I tried:
select substring('first:last' from '.+:')
但这会保留:
,如果没有:
。
But this leaves the :
in and won't work if there is no :
in the string.
推荐答案
使用 split_part()
:
SELECT split_part('first:last', ':', 1) AS first_part
如果分隔符不存在,则返回整个字符串。而且很容易获得第二或第三部分等。
Returns the whole string if the delimiter is not there. And it's simple to get the 2nd or 3rd part etc.
比使用正则表达式匹配的函数快得多。而且由于我们有固定的定界符,所以我们不需要使用正则表达式。
Substantially faster than functions using regular expression matching. And since we have a fixed delimiter we don't need the magic of regular expressions.
相关:
- Split comma separated column data into additional columns
这篇关于第一次出现字符后剪切字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!