Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting by " | " not between square brackets

I need to split a string, but ignoring stuff between square brackets. You can imagine this akin to ignoring stuff within quotes.

I came across a solution for quotes;

(\|)(?=(?:[^"]|"[^"]*")*$)

So;

one|two"ignore|ignore"|three

would be;

one
two"ignore|ignore"
three

However, I am struggling to adapt this to ignore [] instead of ". Partly its down to there being two characters, not one. Partly its down to [] needing to be escaped, and partly its down to me being pretty absolutely awful at regexs.

My goal is to get;

So;

one|two[ignore|ignore]|three

split to;

 one
 two[ignore|ignore]
 three

I tried figuring it out myself but I got into a right mess; (\|)(?=(?:[^\[|\]]|\|][^\[|\]]*\[|\])*$) I am seeing brackets and lines everywhere now.

Help!

like image 767
darkflame Avatar asked Oct 03 '22 08:10

darkflame


1 Answers

This is the adapted version of the "" regex you posted:

(\|)(?=(?:[^\]]|\[[^\]]*\])*$)
(\|)(?=(?:[^ "]| "[^ "]* ")*$) <- "" version for comparison

You replace the 2nd " with \[ and the 1st and 3rd with \]

Working on RegExr

like image 114
OGHaza Avatar answered Oct 13 '22 10:10

OGHaza