POSTGRESQL 位置子串

POSTGRESQL position substring

我有一个简单的问题(我认为)我无法解决: 我有很多这样的标签: 'FOOT05_00120_RIG_1_GOAL_K' 但是所有记录的长度都不一样,我需要一个查询来获取最后一个 _ 之前的所有字符,有人知道我该怎么做吗?

(可能在这样的查询中:

SELECT tag FROM Football

)

感谢大家

您可以使用 REVERSE 函数来确定最后一个连字符的位置,然后将 SUBSTRING()LENGTH() 函数一起应用,例如

WITH Football AS
(
 SELECT 'FOOT05_00120_RIG_1_GOAL_K' AS tag
)
SELECT SUBSTRING( tag, 1, LENGTH(tag) - POSITION('_' IN REVERSE(tag)) ) AS Result
  FROM Football

Demo

这个问题似乎是为regexp_replace()设计的:

select regexp_replace(tag, '(.*)_[^_]*$', '')
from football;

正则表达式解释为:

'(.*)_[^_]*$'
-^ remember this expression for a reference
--^ any character
---^ any number of times
----^ followed by _
-----^ followed by any characters that are not _
----------^ any number of times
-----------^ at the end of the string