I have an array of strings that look like the following:
const stringArray = [
'string1[1] string2[2] string3[3] [4 5]',
'string6[6] string7[7] string8[8] [9 10]'
];
I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:
const splittedArray = [
[
'string1[1]',
'string2[2]',
'string3[3]',
'[4 5]'
],
[
'string6[6]',
'string7[7]',
'string8[8]',
'[9 10]'
]
]
I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.
Whenever I try /(?=\])\s/g
it does not separate the string, whenever I try /(?=\])\s*/
it separates the string and keeps both the ]
and the whitespace
, but does so in the next line (and well, keeps the whitespace).
I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ]
without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ]
hence why I'm trying this solution.
Here is a little code snipper with what I have and what it returns:
const stringArray = [
'string1[1] string2[2] string3[3] [4 5]',
'string6[6] string7[7] string8[8] [9 10]'
];
const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));
console.log(splittedStringArray);
const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));
console.log(anotherSplittedStringArray);
const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));
// The same as the previous one
console.log(splittedByBrackets);
For my case, the answer was: /\w*\[.*?\]/g
(with match instead of split) by Thomas. From what I understood:
The \w*
matches any word (0 or more times)
The \[
matches the [
after a word (or no word, above condition)
The .*?
matches any character excluding line breaks (0 or more times) lazyly, I believe the ?
is to tell to stop matching on the first character(s) otherwise it would search the whole string.
The \]
matches the ]
after what is after the other bracket (which is the above condition).
The /g
flag makes it so it searched for more than one occurrence.