Skip to content
Advertisement

Regex split string at specific set of characters

Suppose I have a string of this nature Set 1 (2) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]. How can I make a regex that starts after (important that it’s after or I can just add it back) every ) character and optionally ends at a ] character, so splitting the string would look something like this?

Set 1 (2) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]
-> [Set 1 (2)], [Set 2 (2)], [Set 3 (2)], [Set 4 (2)]

There might be some empty characters and trailing whitespaces in the created array when using regex but I can remove that. My current try is something like /)(s+).+(]?)/gm but due to the .+ being greedy It goes all the way to the end for each match like so:

Set 1 (2) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]
-> Set 1 (2{) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]}
-> [Set 1 (2]

It also includes the ) when splitting which is undesirable.

Advertisement

Answer

const s = "Set 1 (2) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]";
const m = s.match(/[^)]+(?:))/g);
console.log(m)

To handle the leading whitespace:

const s = "Set 1 (2) Set 2 (2) Set 3 (2) Set 4 (2) [Choose Two]";
const m = s.match(/(?<= |^)[^)]+(?:))/g);
console.log(m)

https://regex101.com/r/qG6G57/1

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement