In JS, I have some strings which need to break down into capture groups. The problem is there are some variations.
String variations:
group3::group4
group2:group3::group4
group1|group3::group4
group1|group2:group3::group4
So far I've able to build the below regex pattern. Which captures when all groups are there. But I wasn't able to capture each group when one or more groups are missing. Can anyone help me with this to figure it out? (Every time each group must be captured by the relevant capture group)
\([^\r\n]+)?\|([^\r\n]+)?:([^\r\n]+)?::([^\r\n]+)?\g
This runs for each string in a loop. So the final result should looks like this for each string.
array(01 => "group1", 02 => null, 03 => "group3", 04 => "group4")
Thanks in advance.
--[ANSWER]--
With the help of @tshiono, I coded the following example, Posting here in case if anyone needed it.
// const text = 'group3::group4';
// const text = 'group2:group3::group4';
// const text = 'group1|group3::group4';
const text = 'group1|group2:group3::group4';
const regex = /(?:([^:|\s]*)\|)?(?:([^:|\s]*):)?([^:|\s]*)::([^:|\s]*)/;
const match = text.match(regex);
console.log( match );
array(01 => "group1", 02 => null, 03 => "group3", 04 => "group4").