Home > Back-end >  Extract from string using regex in SQL (Snowflake)
Extract from string using regex in SQL (Snowflake)

Time:03-03

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.

CodePudding user response:

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

CodePudding user response:

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;

enter image description here

  • Related