sql - regex_substr 提取字符串中的度量单位
问题描述
我是 regexp 的新手,并试图在一个字符串块中提取度量单位。字符串示例如下:
PRODUCT NAME 3.5G
3.5g PRODUCT NAME
PRODUCT NAME 3.5 GRAMS
PRODUCT NAME 3500MG
我如何能够使用 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'
解决方案
一种方法是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')
推荐阅读
- mysql - SQL求和并显示总和值不存在的行
- java - 从增强 for 循环更改为正常 for 循环的问题
- java - Spring + javax.persistence.Query:管理从 H2 和 PosgreSQL DB 原生日期类型到 OffsetDateTime 的类型转换
- kotlin - 带有 Jackson 的 ObjectMapper.readValue() 的 Kotlin UnrecognizedPropertyException
- android - 原因:尝试将不存在的文件添加到类路径:E:\AndroidProjects\GoodCreditNum\app\src\main\AndroidManifest.xml
- solr - Solr查询两个字段错误
- javascript - 查找对象中与给定字符串匹配的所有键的路径
- powershell - 具有独特选择 Powershell 的多个 ComboBox
- windows-machine-learning - 使用 Windows SDK 17763 进行 ML 图像评估接受大小为 227 x 227 的图像
- c++ - 尝试创建表会出现 sql 逻辑错误