【问题标题】:Extract substrings based on multiple conditions in postgresqlpostgresql中根据多个条件提取子串
【发布时间】:2022-08-04 15:16:28
【问题描述】:

我在 postgres 表中有以下列。

col1                                start    end
p.[A138T;S160G;D221_E222delinsGK]   138      138
p.[A138T;S160G;D221_E222delinsGK]   160      160
p.[A138T;S160G;D221_E222delinsGK]   221      222

我正在寻找一种方法来拆分 ;在多行中分隔值。预期的输出是:

col1                                start    end
p.A138T                             138      138
p.S160G                             160      160
p.D221_E222delinsGK                 221      222

我正在使用以下查询,但它不适用于第三行。

select
       case 
            when start = \"end\" and col1 like \'p.[%\' then \'p.\'||(regexp_match(col1, \'([A-Z]\'||start||\'[A-Z])\'))[1] 
            when start != \"end\" and col1 like \'p.[%\' then \'p.\'||(regexp_match(col1, \'[A-Z\\d+_delins]+\'||start||\'[A-Z\\d+_delins]+\'))[1] 
            else col1,
                   
            start,
            end
from table

非常感谢任何帮助!

    标签: postgresql substring


    【解决方案1】:

    我更喜欢substring() 基于正则表达式提取字符串,因此我不必处理regexp_match() 返回的数组。

    select case 
              when col1 like 'p.%' and start = "end" 
                then 'p.'||substring(col1 from concat('[A-Z]', start, '[A-Z]'))
              when col1 like 'p.%' and start <> "end" 
                then 'p.'||substring(col1 from concat('[A-Z]', start, '_[A-Z]', "end", 'delins[^\]]+'))
              else col1
           end as col1, 
           start,
           "end"
    from the_table;
    

    据我所知,第二种选择的正则表达式将_delins 错误地添加到标记“开始”值的正则表达式中。如果这是一个常数值,它不应该是正则表达式“范围”的一部分,因为[delins]' 也会匹配字符串sindel。不确定你是否有意这样做。

    另一种选择是简单地采取“结束”标记之后的所有内容,并通过使用排除关闭]

    substring(col1 from concat('[A-Z]', start, '_[A-Z]', "end", '[^\]]+'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-11
      • 2023-02-25
      • 1970-01-01
      • 2021-05-02
      • 1970-01-01
      • 2017-01-22
      • 2022-08-18
      相关资源
      最近更新 更多