Test string:
*This* is a test.[15] I would like[16] To figure _out how_ to do this.[20]
RegEx:
/\[\d+\]|\*.*\*|_.*_/gu
Actual Results:
Match 1: *This*
Match 2: [15]
Match 3: [16]
Match 4: _out how_
Match 5: [20]
Desired Results:
Match 1: *This*
Match 2: is a test.
Match 3: [15]
Match 4: I would like
Match 5: [16]
Match 6: To figure
Match 7: _out how_
Match 8: to do this.
Match 9: [20]
>Solution :
You may consider this approach that splits the input with capture group and uses filter to remove empty match from the start.
const s = '*This* is a test.[15] I would like[16] To figure _out how_ to do this.[20]'
console.log( s.split(/(\*[^*]*\*|_[^_]+_|\[\d+\])/).filter(Boolean) );
/*
[
"*This*",
" is a test.",
"[15]",
" I would like",
"[16]",
" To figure ",
"_out how_",
" to do this.",
"[20]"
]
*/
RegEx Details:
(: Start capture group\*[^*]*\*: Match substring wrapped in*|: OR_[^_]+_: Match substring wrapped in_|: OR\[\d+\]: Match[number]part
): End capture group