I'm trying to string.matchAll
the following string:
const text = 'textA [aaa](bbb) textB [ccc](ddd) textC'
I want to match the following:
- 1st:
"textA [aaa](bbb)"
- 2nd:
" textB [ccc](ddd)"
- 3rd:
" textC"
NOTE: The capturing groups are already present in the regex
. That's what I need.
It's almost working, but so far I couldn't think of a way to match the last part of the string, which is just " textC"
, and doesn't have the [*](*)
pattern.
What am I doing wrong?
const text = 'textA [aaa](bbb) textB [ccc](ddd) textC'
const regexp = /(.*?)\[(.+?)\]\((.+?)\)/g;
const array = Array.from(text.matchAll(regexp));
console.log(JSON.stringify(array[0][0]));
console.log(JSON.stringify(array[1][0]));
console.log(JSON.stringify(array[2][0]));
UPDATE:
Besides the good solutions provided in the answers below, this is also an option:
const text= 'textA [aaa](bbb) textB [ccc](ddd) textC'
const regexp = /(?!$)([^[]*)(?:\[(.*?)\]\((.*?)\))?/gm;
const array = Array.from(text.matchAll(regexp));
console.log(array);