删除 if(CC_DEBUG) {} 这个正则是怎么写的?

删除 if(CC_DEBUG) {…} 这个正则是怎么写的?

尝试去写, 有嵌套比较麻烦. 求正则, 官方的编译没找到.

因为我定义了很多其他测试标签, 求这个正则

后面花括号是要换行的吧? 感觉不好匹配, 容易出错. 不如在范围内替换掉CC_DEBUG为自己的变量

直接编辑器全局搜索替换不行吗…

正则匹配右边 } 比较难。你可以写字符串遍历,性能虽然比不过正则,但是也可以解决你的问题。

  const reg1 = /(if[\s|\n|\r]*\([\s|\n|\r]*CC_DEBUG[\s|\n|\r]*\)[\s|\n|\r]*{[^{}]*)/gs;

  const reg2 = /({[^{}]*)/gs;

  const reg3 = /(}[^{}]*)/gs;

  function replace(str) {

    let newStr = "";

    const results = [...str.matchAll(reg1)];

    if (results.length === 0) {

      return str;

    }

    newStr += str.substring(0, results[0].index);

    for (let i = 0; i < results.length; i++) {

      let result = results[i];

      let start = result.index,

        end = -1,

        lastIndex = result.index + result[0].length;

      max = i < results.length - 1 ? results[i + 1].index : str.length;

      let count = 0;

      while (true) {

        if (str[lastIndex] === "{") {

          count++;

          reg2.lastIndex = lastIndex;

          let res = reg2.exec(str);

          lastIndex = res.index + res[0].length;

        } else if (str[lastIndex] === "}") {

          count--;

          if (count < 0) {

            end = lastIndex + 1;

            break;

          }

          reg3.lastIndex = lastIndex;

          let res = reg3.exec(str);

          if (res) {

            if (res.index + res[0].length >= max) {

              end = lastIndex + 1;

              break;

            } else {

              lastIndex = res.index + res[0].length;

            }

          } else {

            throw new Error("code error");

          }

        } else {

          throw new Error("error" + str[lastIndex]);

        }

      }

      newStr += str.substring(end, max);

    }

    return newStr;

  }

这种复杂的环境最准确的还是使用语法分析器
一般使用lex与yacc
如果真的要做的话,推荐使用python来写, python带有这2个库

如果用语法分析的话, 不如直接上ast
https://segmentfault.com/a/1190000016231512

不难, 直接使用python写一个parser判别很快的

使用字串搜索"if(CC_DEBUG)“定位后, 继续向后扫描字串
当遇见”{“计数+1, 遇见”}"计数-1, 直到计数为0时, 表示if判断式结束, 将中间走访过的字符移除即可

原理也很简单, 因为文法正确的代码"{“和”}"是对称的