c# - 只会更改顶级函数声明的正则表达式
问题描述
我有包含以下形式的函数的 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
请注意,(?2)
默认情况下 .net 不支持递归 ( ),因此您必须使用另一个用于 C# 的 RegEx 引擎,例如用于 .Net 的 PCRE。
如果你不想使用另一个引擎,你可以(?2)
用(.*{(?2)}.*)*
递归替换你想要的深度,以匹配嵌套的 if 循环等,最后用(?2)
替换.*
。结果应如下所示:
function (.+{.*(.*{(.*{(.*{(.*{(.*{(.*{(.*)}.*)*}.*)*}.*)*}.*)*}.*)*}.*)*.*?})
推荐阅读
- javascript - 扩展试图将 CSS 注入网页而不是将 CSS 注入自身
- ios - 计算机和 iPhone 之间的 App-to-App 通信
- python - 完成“破碎”图像的轮廓
- azure - Azure 逻辑应用中的随机列表
- bash - 如何使用 sed 和正则表达式替换文件中的部分行?
- c++ - 无法让它重新循环。C++
- python-3.x - 递归python3代码中的溢出堆栈
- arrays - 当数组具有相同值的两个实例时,快速排序算法中的无限循环
- django - 如何在 DRF 的视图集中使用自定义列表方法和自定义操作?
- ios - 为什么 UIPickerView 不显示图片?