简体   繁体   English

在 SQL (Snowflake) 中使用正则表达式从字符串中提取

[英]Extract from string using regex in SQL (Snowflake)

I have a database field which contains a long string of text:我有一个包含一长串文本的数据库字段:

Date: 02/03/22 Customer Price: 500 Total Price: 701.56 Paid to Date: 304.10 Confirmed: TRUE

What would be the best way of extracting out certain numbers from this string?从该字符串中提取某些数字的最佳方法是什么? For example, how could I extract 'Total Price' (701.56) and 'Paid to Date' (304.10)?例如,我如何提取“总价”(701.56) 和“已付日期”(304.10)? I think I need to use REGEXP_SUBSTR but not I'm 100% sure.我想我需要使用REGEXP_SUBSTR但我不是 100% 确定。 For example:例如:

select REGEXP_SUBSTR(my_field_name, 'Total Price: (SOME-REGEX)') as total_price,
select REGEXP_SUBSTR(my_field_name, 'Paid To Date: (SOME-REGEX)') as paid_to_date,
from my_table

I only need to return the values, not the preceding text.我只需要返回值,而不是前面的文本。

Here is one way of doing it:这是一种方法:

set my_string='Date: 02/03/22 Customer Price: 500 Total Price: 701.56 Paid to Date: 304.10 Confirmed: TRUE';
select REGEXP_SUBSTR($my_string, 'Total Price: (\\d*.\\d*)',1,1,'e') as total_price;
select REGEXP_SUBSTR($my_string, 'Paid to Date: (\\d*.\\d*)',1,1,'e') as paid_to_date;

Results:结果:

701.56
304.10
SELECT 'Date: 02/03/22 Customer Price: 500 Total Price: 701.56 Paid to Date: 304.10 Confirmed: TRUE' as a , 
REGEXP_SUBSTR(a,'Total Price: [0-9]*.[0-9]*') as total_price,
REGEXP_SUBSTR(a,'Paid to Date: [0-9]*.[0-9]*') as paid_to_date;

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM