I want to splits a string on '_'
and replace 3rd group with 'oooo'
.
Is there any way to do it simply and without assuming there’s exactly 5 groups?
CONCAT( SPLIT_PART(test, '_', 1)
,SPLIT_PART(test, '_', 2)
,'OOOO'
,SPLIT_PART(test, '_', 4)
,SPLIT_PART(test, '_', 5)
)
Example:
'GjHf00_i8S7b_tst00_UL000_perce'
turns into this
'GjHf00_i8S7b_oooo_UL000_perce'
3
Answers
demo at db<>fiddle
It’s looking for substrings of 1 or more non-underscores, starting from position 1 and trying to replace the 3rd hit:
[]
is a group of allowed characters^
inside a group means it’s a group you wish to exclude_
is just the underscore+
means you’re looking for 1 or more of thatWhere to start and which match to replace is handled by the rest of
regexp_replace()
params:If you’re fine with the assumption that you always have 5 groups, your idea would work as long as you swap out
concat()
forconcat_ws()
. Otherwise you’d lose the underscores you’re splitting on:You could also use a regular expression with back references, like:
Typically not faster.
fiddle
Try matching:
and replacing with:
See: regex101 and fiddle
Explanation
MATCH:
^
: start of string((?:[^_]+_){2})
: Capture the first two blocks to group 1([^_]+)
: Capture the third block to group 2REPLACE:
1
: Keep the startoooo
: Replace third block with "oooo"