Complex regex to split up a string

前端 未结 1 471
无人及你
无人及你 2021-01-27 02:21

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:

{s         


        
相关标签:
1条回答
  • 2021-01-27 02:36

    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 讨论(0)
提交回复
热议问题