I am trying to add a comma and a space to my strings. Here are some examples:
{ELEPHANT:1, FENNEC_FOX:1NAKED_MOLE:1URCHIN:2}
{DUNG_BEETLE:12URCHIN:1}
{DUNG_BEETLE:1FENNEC_FOX:1URCHIN:2}
Notice the inconsistent lack of ", ". I would like to outcome to be
{ELEPHANT:1, FENNEC_FOX:1, NAKED_MOLE:1, URCHIN:2}
{DUNG_BEETLE:1, URCHIN:1}
{DUNG_BEETLE:1, FENNEC_FOX:1, URCHIN:2}
I think I need to use REGEXP_REPLACE(my_string, ':[0-9]+[a-z_A-Z]', replacement)
. But I’m not quite sure how to make replacement
be the colon and whatever the number is, a comma and a space, and whatever the matching letter is.
2
Answers
This expression gets your desired result (fastest in a quick test with 100k rows):
Core features are the positive lookahead
(?=[a-zA-Z])
and the 4th parameter'g'
.Working with a positive lookbehind is slower for this – as hinted by Nick.
fiddle
Related answer with more explanation:
Your regex is fine, although you can simplify it by using
d
in place of[0-9]
andw
in place of[a-z_A-Z]
. You then need to use capturing groups to save the matched text and insert it into the replacement string:Output:
If you’re trying to convert this into valid JSON, you’ll need a second step to enclose the keys in double quotes:
Output:
Demo on dbfiddle.uk