postgresql 在第一次出现字符后剪切字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29522829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:50:57  来源:igfitidea点击:

Cut string after first occurrence of a character

sqlstringpostgresqlpattern-matchingdelimiter

提问by Gismo Ranas

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:

我有像“keepme:cutme”或“string-without-separator”这样的字符串,它们应该分别变成“keepme”和“string-without-separator”。这可以在 PostgreSQL 中完成吗?我试过:

select substring('first:last' from '.+:')

But this leaves the :in and won't work if there is no :in the string.

但是:如果:字符串中没有,这会留下in 并且将不起作用。

回答by Erwin Brandstetter

Use split_part():

使用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.

比使用正则表达式匹配的函数快得多。因为我们有一个固定的分隔符,所以我们不需要正则表达式的魔力。

Related:

有关的:

回答by vol7ron

regexp_replace() may be overload for what you need, but it also gives the additional benefit of regex. For instance, if strings use multiple delimiters.

regexp_replace() 可能会满足您的需要,但它也提供了regex的额外好处。例如,如果字符串使用多个分隔符。

Example use:

使用示例:

select regexp_replace( 'first:last', E':.*', '');

回答by rchacko

SQL Select to pick everything after the last occurrence of a character

SQL Select 选择最后一次出现字符后的所有内容

select right('first:last', charindex(':', reverse('first:last')) - 1)