Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to split a user defined string

I have to split a user defined string which can look something like this

[test1]-[test2]>>[test3]Some Text:[test4]|test:[test199]|some_text:[test0][test100]

And at the end I want to get a list in js which looks like this

["[test1]", "-", "[test2]", ">>", "[test3]", "Some Text:", "[test4]", "|test:", "[test199]", "|some_text:", "[test0]", "[test100]"]

So I want the text to be splitted by the variables in the [] brackets and everything which is not in brackets.

The problem here is that I can only get a solution for everything which is in [] brackets or a more or less static solution.

Everything in [] brackets

(\[.*?\])

Not completely correct regex

((\[.*?\]))|([a-zA-Z0-9->:|_ ]*(?!\]))

This will for example not work with a text like this

[test100
like image 211
JonasR Avatar asked Sep 12 '26 16:09

JonasR


1 Answers

Since you do not care if there are nested brackets or not, you may use

s.split(/(\[[^\][]*])/).filter(Boolean)

The (\[[^\][]*]) pattern matches and captures into Group 1 a [, then any 0+ chars other than [ and ] and then ], and uses it to split a string into chunks while saving both matched and non-matched chunks into the resulting array.

If there are adjoining chunks or it is at the start/end of the string there may appear empty items, and .filter(Boolean) gets rid of them.

See the JS demo:

console.log(
    "[test1]-[test2]>>[test3]Some Text:[test4]|test:[test199]|some_text:[test0][test100]"
        .split(/(\[[^\][]*])/).filter(Boolean)
)
like image 89
Wiktor Stribiżew Avatar answered Sep 15 '26 05:09

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!