我有包含以下形式函数的 Javascript 文件:
function xyz(a,b,c,...){
....
}
为了 Typescript 迁移,我想将它们更改为以下形式:
private xyz(a,b,c,...){
....
}
我可以使用“function(.*)\(.*\)”但是如果有嵌套函数,我需要保持它们不变。
对此合适的 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
请注意,.net 默认不支持递归 ((?2)),因此您必须为 C# 使用另一个 RegEx 引擎,例如 PCRE for .Net .
如果您不想使用其他引擎,可以将 (?2) 替换为 (.*{(?2)}.*)*递归到你想要的深度,以匹配嵌套的 if 循环等,最后将 (?2) 替换为 .*。 结果应该是这个样子: 函数 (.+{.*(.*{(.*{(.*{(.*{(.*{(.*{(.*)}.*)*}.*)*}。 *)*}.*)*}.*)*}.*)*.*?})
