PostgreSQL中的字符串匹配模式

3
我有一个long_name列。我需要为此列获取短名称。短名称由长名称中"_"后的第一个字符组成。
例如: long_name: '_Michael_Smith' 应产生 'MS' 短名称 long_name: '_Michael_John_Smith' 应产生 'MJS' 短名称
我可以使用以下方式获取第一个字符: substring(long_name from position('_' in long_name)+1 for 1) as short_name。
在查询中如何获取其余字符?

出于性能考虑,您可能只需添加一个新列并通过编程确定短名称。这意味着在两个列之间同步值,但查询可能会运行得更快。另一种可能性是根据查询结果动态地通过编程确定值。如果您决定仅使用一个列并需要在查询结果中获取短名称值,则可以尝试使用regexp_replace:http://www.postgresql.org/docs/current/static/functions-matching.html - aro_tech
1个回答

1
使用 regexp_replace()
with example(long_name) as (
    values
        ('_Michael_Smith'),
        ('_Michael_John_Smith') 
    )
select 
    long_name, 
    regexp_replace(long_name, '_(.)[^_]+', '\1', 'g') short_name
from example;

      long_name      | short_name 
---------------------+------------
 _Michael_Smith      | MS
 _Michael_John_Smith | MJS
(2 rows)

阅读:

POSIX正则表达式


作为澄清:这将用第一个捕获组“(.)”替换整个匹配项_(.)[^_]+ - Andomar

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