Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

javascript - JS Regex to match everything inside braces (including nested braces): "{ I want this {and this} and this in one string }"

Meaning that I simply want to strip the enclosing braces. I can match "{ this kind of stuff }" with:

"{stuff}".match(/{([^}]*)}/)[1]

Am I asking too much here?

Another example, I've got this javascript code as string:

{
    var foo = {
        bar: 1    
    };

    var foo2 = {
        bar: 2    
    };
}

I want to strip only the outside braces:

var foo = {
    bar: 1
};

var foo2 = {
    bar: 2
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this (I based my code on this answer). It also knows to ignore brackets in strings and comments (single-line and multi-line) - as noted in the comment section of that answer:

var block = /* code block */
    startIndex = /* index of first bracket */,
    currPos = startIndex,
    openBrackets = 0,
    stillSearching = true,
    waitForChar = false;

while (stillSearching && currPos <= block.length) {
  var currChar = block.charAt(currPos);

  if (!waitForChar) {
    switch (currChar) {
      case '{':
        openBrackets++; 
        break;
      case '}':
        openBrackets--;
        break;
      case '"':
      case "'":
        waitForChar = currChar;
        break;
      case '/':
        var nextChar = block.charAt(currPos + 1);
        if (nextChar === '/') {
          waitForChar = '
';
        } else if (nextChar === '*') {
          waitForChar = '*/';
        }
    }
  } else {
    if (currChar === waitForChar) {
      if (waitForChar === '"' || waitForChar === "'") {
        block.charAt(currPos - 1) !== '\' && (waitForChar = false);
      } else {
        waitForChar = false;
      }
    } else if (currChar === '*') {
      block.charAt(currPos + 1) === '/' && (waitForChar = false);
    }
  }

  currPos++ 
  if (openBrackets === 0) { stillSearching = false; } 
}

console.log(block.substring(startIndex , currPos)); // contents of the outermost brackets incl. everything inside

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...