Rahul
Rahul

Reputation: 2307

How do I split a string with complex delimiters using regex?

I need to parse a string based on a regular expression and return a collection of strings.

The string I need to parse resembles the following:

"NM2RAJ/Fred MR(IR1234)/MISAMISS1BLACK/DROID MR 1BROWN/JACK(IECSL/HALDUW/13JUN12)"

From the above string I would like to return an array that contains the following strings from the original:

O/P=>

array temp=["NM","RAJ/Fred MR(IR1234)/MISAMISS","BLACK/DROID MR ","BROWN/JACK(IECSL/HALDUW/13JUN12)"]

The data should be partitioned on numbers which are not contained in parentheses.

Upvotes: 0

Views: 215

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174796

Use negative lookahead based regex.

var s = "NM2RAJ/Fred MR(IR1234)/MISAMISS1BLACK/DROID MR 1BROWN/JACK(IECSL/HALDUW/13JUN12)"
alert(s.split(/\d+(?![^()]*\))/))

\d+(?![^()]*\)) matches any number which isn't followed by, any character but not of ( or ), zero or more times and a closing parenthesis ) . So this matches all the number which was not present inside the paranthesis. I assumed that your parenthesis are properly closed.

Upvotes: 1

Related Questions