Home > Blockchain >  How can I split a string via first level square brackets?
How can I split a string via first level square brackets?

Time:10-14

I have a string like this:

key[type=order][0].item[id={getVal(obj[type=item][0].id)}]

and I want to split this string as like:

 [
     ['key', '[type=order]', '[0]'],
     ['item', '[id={getVal(obj[type=item][0].id)}]']
 ]

Firstly I split string via first level dot:

const str = 'key[type=order][0].item[id={getVal(obj[type=item][0].id)}]';
const arr = str.split(/\.(?![^[]*])/).filter(Boolean);

This generated array like this:

['key[type=order][0]', 'item[id={getVal(obj[type=item][0].id)}]']

And after that I want to split all array item via first level square bracket with:

arr.map(item => item.split(/(\[. ?\])/).filter(Boolean))

This generated array:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item]', '[0]', '.id)}]']
]

I want to split items only first level square brackets not nested. How can I do this with regex in javascript?

CodePudding user response:

this should do it on your final split

arr.map(item => item.split(/(\[[^\]] \(.*\).*\])|(\[. ?\])/).filter(Boolean))

Which generates the array:

[
    ['key', '[type=order]', '[0]'],
    ['item', '[id={getVal(obj[type=item][0].id)}]']
]

The regex is /(\[[^\]] \(.*\).*\])|(\[. ?\])/ and the first part of that looks for any square brackets with parentheses inside, and discounts any square brackets within those. After the | (or) your original regex runs!

  • Related