使用split_part()函数获取返回值的最后一部分

3

我可以帮你翻译。以下是需要翻译的内容:

我有一个由正斜杠分隔的文件路径字符串。我想根据正斜杠拆分它们并返回文件名。

输入

//a/b/c/xyz.png

输出

xyz.png

当前解决方案

SELECT REVERSE(SPLIT_PART(REVERSE('//a/b/c/xyz.py'), '/', 1)) as "file_name";

有没有更有效的方法来完成这个任务?
3个回答

4
"

regexp_match()更为简洁:

"
select (regexp_match('//a/b/c/xyz.py', '[^/]+$'))[1]

2
PostgreSQL 14将支持负索引,因此操作将变得简单明了。

split_part

Splits string at occurrences of delimiter and returns the n'th field (counting from one), or when n is negative, returns the |n|'th-from-last field.

split_part('abc,def,ghi,jkl', ',', -2) → ghi
在这个特定的情景中:
SELECT SPLIT_PART('//a/b/c/xyz.py', '/', -1) as "file_name";

1

我会使用regexp_replace()函数来移除最后一个斜杠(包括它本身)之前所有的字符:

select regexp_replace('//a/b/c/xyz.png', '.*/', '')

DB Fiddle演示:

| regexp_replace |
| :------------- |
| xyz.png        |

您也可以使用substring(),这可能更有效:

substring('//a/b/c/xyz.png' from '[^/]*$')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接