Home > Software design >  How do I make a regex that seperates this string?
How do I make a regex that seperates this string?

Time:08-07

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.

CodePudding user response:

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

CodePudding user response:

The simplest would be to use String.split with this regex:

/(?<=\))/g

It simply looks behind for a ) and then splits the text into an array.

However, you then need to remove the last item in the array (which will contain [Choose Two]).

Then you have array with each Set.

You can play with it here.

  • Related