4

这意味着我只是想剥离封闭的大括号。我可以将“{这种东西}”与:

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

我在这里问太多了吗?

另一个例子,我有这个 javascript 代码作为字符串:

{
    var foo = {
        bar: 1    
    };

    var foo2 = {
        bar: 2    
    };
}

我只想剥掉外面的大括号:

var foo = {
    bar: 1
};

var foo2 = {
    bar: 2
}
4

2 回答 2

9

试试这个(我的代码基于这个答案)。它还知道忽略字符串和注释(单行和多行)中的括号 - 如该答案的注释部分所述:

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 = '\n';
        } 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
于 2014-11-23T10:58:49.380 回答
1

我同意 Lucero 的观点,即正则表达式不是为此而设计的,而是为了回答您的问题:

问题是你匹配除了}. 但是由于您要匹配的内部数据本身包含 a },因此外部大括号的内容不匹配。

{
    var foo = {
        bar: 1
==> };

    var foo2 = {
        bar: 2    
==> };
}

您可以使用此正则表达式:

{([\S\s]*)}

解释:

{                   match opening {
    (               group
        [\S\s]      match everything, workaround for the missing s option in JS
              *     greedy, makes it match as much as possible
    )               end group
}                   match closing }
于 2013-03-30T11:11:57.093 回答