首页 > 解决方案 > 从 regexp_matches 结果中获取第二个匹配项

问题描述

我有一个name看起来像这样的列:

'1234567 - 7654321 - some - more - text'

我需要得到一个字符串"7654321"。我坚持以下几点:

SELECT regexp_matches('1234567 - 7654321 - some - more - text', '\d+', 'g');

regexp_matches
----------------
{1234567}
{7654321}

(2 rows)

我怎么做我想要的?也许有比regexp_matches- 很乐意考虑的更好的选择。谢谢!

标签: sqlregexpostgresql

解决方案


regexp_matches()返回一个表,因此您可以在 from 子句中将其与with ordinality选项一起使用:

SELECT t.value
from regexp_matches('1234567 - 7654321 - some - more - text', '\d+', 'g') with ordinality as t(value,idx)
where t.idx = 2;

请注意,value它仍然是一个数组,要获取您可以使用的实际数组元素:

SELECT t.value[1]
from regexp_matches('1234567 - 7654321 - some - more - text', '\d+', 'g') with ordinality as t(value,idx)
where t.idx = 2;

推荐阅读