1

Given input string as

'PARAM_1=TRUE,THRESHOLDLIST=kWh,2000,Gallons,1000,litre,3000,PARAM_2=TRUE,PARAM_3=abc,123,kWh,800,Gallons,500'

and unit_param = 'Gallons' I need to extract value of unit_param (Gallons) which is 1000 using postgresql regex functions.

As of now, I have a function that first extracts value for THRESHOLDLIST which is "kWh,2000,Gallons,1000,litre,3000", then splits and loops over the array to get the value.

Can I get this efficiently using regex.

SELECT substring('PARAM_1=TRUE,THRESHOLDLIST=kWh,2000,Gallons,1000,litre,3000,PARAM_2=TRUE,PARAM_3=abc,123,xyz' FROM '%THRESHOLDLIST=#".........#",%' FOR '#')
1
  • I assume switching that to a better (parsable) format (e.g. JSON) isn't an option? That would make things a lot easier Commented Jan 28, 2021 at 15:41

2 Answers 2

1

Use substring() with the target input grouped:

substring(myCol, 'THRESHOLDLIST=[^=]*Gallons,([0-9]+)')

The expression [^=]* means “characters that are not =”, so it won’t match Gallons within another parameter.

Sign up to request clarification or add additional context in comments.

3 Comments

the occurrence of Gallon could be in other parameters too. I want to confirm the value is coming from the THRESHOLDLIST.
@FurqanShaikh better update your question to say that then, plus update your example to include two occurrences of Gallon to make it clear.
@furq I’ve updated the regex to only match within THRESHOLDLIST
0

select Substring('PARAM_1=TRUE,THRESHOLDLIST=kWh,2000,Gallons,1000,litre,3000,PARAM_2=TRUE,PARAM_3=abc,123,xyz' from 'Gallons,\d*');

returns Gallons,1000

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.