Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a regular expression for this scenario?

For example, I have a string :

/div1/div2[/div3[/div4]]/div5/div6[/div7]

Now I want to split the content by "/" and ignore the content in the "[ ]".

The result should be:

  1. div1
  2. div2[/div3[/div4]]
  3. div5
  4. div6[/div7]

How can I get the result using regular expression? My programming language is JavaScript.

like image 535
Mike108 Avatar asked Mar 01 '23 12:03

Mike108


1 Answers

You can't do this with regular expressions because it's recursive. (That answers your question, now to see if I can solve the problem elegantly...)

Edit: aem tipped me off! :D

Works as long as every [ is followed by /. It does not verify that the string is in the correct format.

string temp = text.Replace("[/", "[");
string[] elements = temp.Split('/').Select(element => element.Replace("[", "[/")).ToArray();
like image 51
Sam Harwell Avatar answered Mar 03 '23 09:03

Sam Harwell