Imagine a text like in this example:
some unimportant content some unimportant content [["string1",1,2,5,"string2"]] some unimportant content some unimportant content
I need a REGEX pattern which will match the parts in [[ ]]
and I need to match each part individually separated by commas.
I already tried
const regex = /[[(([^,]*),?)*]]/g const found = result.match(regex)
but it doesn’t work as expected. It matches only the full string and have no group matches. Also it has a catastrophic backtracking according to regex101.com if the sample text is larger.
Output should be a JS array ["string1", 1, 2, 5, "string2"]
Thank you for your suggestions.
Advertisement
Answer
What about going with a simple pattern like /[[(.*)]]/g
and then you’d just have to split the result (and apparently strip those extra quotation marks):
const result = `some unimportant content some unimportant content [["string1",1,2,5,"string2"]] some unimportant content some unimportant content`; // const found = /[[(.*)]]/g.exec(result); const found = /[[(.*?)]]/g.exec(result); // As suggested by MikeM const arr_from_found = found[1].replace(/"/g, '').split(','); console.log(arr_from_found); // [ 'string1', '1', '2', '5', 'string2' ]