0

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.

3
  • 1
    Repeated capturing groups are just like this, you will always have the last value captured in the group. So, match the whole and split (or match to extract, as you wish) as the post-action. Commented Jun 8, 2022 at 16:35
  • Try this shortest solution text.match(/(?<=\[)(\[.*?])(?=])/g).map(JSON.parse) Commented Jun 8, 2022 at 16:51
  • Aside: "catastrophic backtracking according to regex101" — if you've tried it out on regex101 you should "Save & Share" and put the link to it in your question. Commented Jun 8, 2022 at 17:07

1 Answer 1

3

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' ]
Sign up to request clarification or add additional context in comments.

3 Comments

Rather than matching greedily with .*, match lazily with .*?, otherwise you may match more than you should. For example, try "one [[two]] three [[four]] five" with your regex.
@MikeM Oh, very nice! I've never known about that - would have actually saved me a ton of headache. That's amazing.
But .*? will fail in case of [["string[[1]]",1,2,5,"string[[2]]"]]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.