简体   繁体   中英

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)? I think I need to use REGEXP_SUBSTR but not I'm 100% sure. 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;

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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