首页 > 解决方案 > 只会更改顶级函数声明的正则表达式

问题描述

我有包含以下形式的函数的 Javascript 文件:

function xyz(a,b,c,...){
....
}

为了 Typescript 迁移,我想将它们更改为以下形式:

private xyz(a,b,c,...){
....
}

我可以使用 " function(.*)\(.*\)" 但如果有嵌套函数,我需要保持它们不变。

什么是正确的 C# RegEx?

标签: c#regex

解决方案


匹配: function (.+{.*(.*{(?2)}.*)*.*?})使用多行参数

然后替换为: private \1

此 RegEx 完全匹配函数,包括任何嵌套函数/if 语句等,因此您只能替换最外面的函数。

解释

function                Matches function keyword
         (              Starts capture group
          .+            Matches function name and parameters
            {           Opens function
             .*         Matches any code in function
               (        Starts new capture group (2) for catching internal curly braces
                .*      Matches any code in function
                  {     Matches opening curly brace
                   (?2) Matches capture group (2), to match any code and curly braces inside
                  }     Matches closing curly brace
                .*      Matches any code
              )*        Closes capture group (2) and allows it to be repeated
           .*?          Matches any code, until next curly brace
          }             Matches closing curly brace
         )              Closes capture group

请注意,(?2)默认情况下 .net 不支持递归 ( ),因此您必须使用另一个用于 C# 的 RegEx 引擎,例如用于 .Net 的 PCRE

如果你不想使用另一个引擎,你可以(?2)(.*{(?2)}.*)*递归替换你想要的深度,以匹配嵌套的 if 循环等,最后用(?2)替换.*。结果应如下所示: function (.+{.*(.*{(.*{(.*{(.*{(.*{(.*{(.*)}.*)*}.*)*}.*)*}.*)*}.*)*}.*)*.*?})


推荐阅读