首页 > 解决方案 > regex_substr 提取字符串中的度量单位

问题描述

我是 regexp 的新手,并试图在一个字符串块中提取度量单位。字符串示例如下:

我如何能够使用 redshift 中的 regex_substr 函数从上述字符串中提取 3.5G。目前使用案例风格

when regexp_substr(trim(upper(productname)), '3.5G') = '3.5G' then '3.5G'

when regexp_substr(trim(upper(productname)), ' .5G') = ' .5G' then '.5G'

when regexp_substr(trim(upper(productname)), ' 1/8TH') = ' 1/8TH' then '3.5G'
when regexp_substr(trim(upper(productname)), ' 1/4') = ' 1/4' then '7G'
when regexp_substr(trim(upper(productname)), ' 1G') = ' 1G' then '1G'
when regexp_substr(trim(upper(productname)), ' 2G') = ' 2G' then '1G'
when regexp_substr(trim(upper(productname)), ' 1.75G') = ' 1.75G' then '1.75G'
when regexp_substr(trim(upper(productname)), ' 7G') = ' 7G' then '7G'

when regexp_substr(trim(upper(productname)), ' 1/2 ') = ' 1/2 ' and producttype = 'FLOWER' then '14G'
when regexp_substr(trim(upper(productname)), ' 14G') = ' 14G' then '14G'

when regexp_substr(trim(upper(productname)), ' 3.5 GRAM') = ' 3.5 GRAM' then '3.5G'
when regexp_substr(trim(upper(productname)), ' EIGHTH') = ' EIGHTH' then '3.5G'
when regexp_substr(trim(upper(productname)), ' 1 GRAM') = ' 1 GRAM' then '1G'
when regexp_substr(trim(upper(productname)), ' 1.75 GRAM') = ' 1.75 GRAM' then '1.75G'
when regexp_substr(trim(upper(productname)), ' 7 GRAM') = ' 7 GRAM' then '7G'
when regexp_substr(trim(upper(productname)), '14 GRAM') = '14 GRAM' then '14G'

when regexp_substr(trim(upper(productname)), ' 5 MILLIGRAM') = ' 5 MILLIGRAM' then '5MG'
when regexp_substr(trim(upper(productname)), ' 5MG') = ' 5MG' then '5MG'
when regexp_substr(trim(upper(productname)), ' 10MG') = ' 10MG' then '10MG'
when regexp_substr(trim(upper(productname)), ' 25MG') = ' 25MG' then '25MG'

标签: sqlregexamazon-redshift

解决方案


一种方法是regexp_replace()

with t as (
      select 'PRODUCT NAME 3.5G' as str union all
      select '3.5g PRODUCT NAME' as str union all
      select 'PRODUCT NAME 3.5 GRAMS' as str union all
      select 'PRODUCT NAME 14 GRAM'
      )
select t.*, regexp_replace(' ' || str, '^.*[^.0-9]([\.0-9]+) ?[gG].*$', '\1')
from t;

您还可以使用:

regexp_replace(str, '(^.*[^.0-9]|^)([\.0-9]+) ?[gG].*$', '\2')

推荐阅读