Say I have a string like
"item:(one|two|three), item2:(x|y)"
Is there a single regex that could “factor” it into
"item:one, item:two, item:three, item2:x, item2:y"
Or must I resort to splitting and looping?
If I must split it up then how do I even turn
"item:(one|two|three)"
into
"item:one, item:two, item:three"
if the amount of things between the parentheses is variable? Are regexes useless for such a problem?
You could do it with a callback function:
For every item, the first parentheses in the regex capture the item’s name (i.e
item) and the second set of (unescaped) parentheses capture the string of all values (i.eone|two|three). The latter are then split at|and joined together with, itemname:and then there is another item name appended to the beginning of the result.This is probably the easiest way to combine regexes to find your data and split and join to build your new regex. The problem why it is not easier is, that you cannot capture an arbitrary number of consecutive values (
one|two|three) in different capturing groups. You would only get the last one, if you tried to capture them individually.