开发者

Complex regex to split up a string

I need some help with a regex conundrum pls. I'm still getting to grips with it all - clearly not an expert!

Eg. Say I have a complex string like so:

{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}

First of all I want to split the string into an array by using the pipe, so it is effectively like:

{something:here}{examp.le:!/?foo|bar}BLAH

and

{something/else:here}:{and:here\\}(.)}

But notice that there is a pipe within the curly brackets to ignore... so need to work out the regex expression for this. I was using indexOf originally, but because I now have to take into account pipes being within the curly brackets, it complicates things.

And it开发者_StackOverflow中文版 isn't over yet! I also then need to split each string into separate parts by what is within the curly brackets and not. So I end up with 2 arrays containing:

Array1

{something:here}
{examp.le:!/?foo|bar}
BLAH

Array2

{something/else:here}
:
{and:here\\}(.)}

I added a double slash before the first closing curly bracket as a way of saying to ignore this one. But cannot figure out the regex to do this.

Can anyone help?


Find all occurrences of "string in braces" or "just string", then iterate through found substrings and split when a pipe is encountered.

str = "{something:here}{examp.le:!/?foo|bar}BLAH|{something/else:here}:{and:here\\}(.)}"

var m = str.match(/{.+?}|[^{}]+/g)
var r = [[]];
var n = 0;
for(var i = 0; i < m.length; i++) {
   var s = m[i];
   if(s.charAt(0) == "{" || s.indexOf("|") < 0)
       r[n].push(s);
   else {
      s = s.split("|");
      if(s[0].length) r[n].push(s[0]);
      r[++n] = [];
      if(s[1].length) r[n].push(s[1]);
   }
}

this expr will be probably better to handle escaped braces

  var m = str.match(/{?(\\.|[^{}])+}?/g
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜