I need help splitting the string below using REGEXP_SPLIT_TO_ARRAY
in a Postgres function:
keyone="valone" key_two="val two" KEY_THREE=val three keyfour="http://sample.domain?par1=val1&par2=val2" keyFIVE=valfive
and the resultant array should look like this:
(keyone="valone",key_two="val two",KEY_THREE=val three,keyfour="http://sample.domain?par1=val1&par2=val2",keyFIVE=valfive)
I ended up with this
myarray := REGEXP_SPLIT_TO_ARRAY(mystring, E'\s(?=([^"]*"[^"]*")*[^"]*$)');
but it is failing to split when value contains space and not enclosed in double quotes (KEY_THREE=val three).
2
Answers
Try the following regular expression
(w+)=(?:"([^"]+)"|((?:(?!s+w+=).)+))
.This regular expression pattern consists of two main parts:
(w+)
: This part captures a word character sequence. Thew
represents any word character (letters, digits, or underscores), and the+
indicates that one or more word characters should be captured.=(?:"([^"]+)"|((?:(?!s+w+=).)+))
: This part matches the equal sign=
followed by a value. It uses a non-capturing group(?:...)
to match either a quoted string("([^"]+)")
or a non-quoted string(((?:(?!s+w+=).)+))
."([^"]+)"
: This subpattern captures a quoted string. It matches a double quote"
followed by one or more characters that are not a double quote([^"]+)
, and then another double quote"
.((?:(?!s+w+=).)+)
: This subpattern captures a non-quoted string. It matches one or more characters.
that are not followed by a space, one or more word characters, an equal sign, and more word characters((?!s+w+=))
.The regex explanation is borrowed from here.
Results:
Try it on db<>fiddle.
Write a
FUNCTION
and then call the function usingFunction here
The Result would be