我需要在VS解决方案中找到具有特定属性的所有函数,并在每个函数的末尾和开头插入一行代码。为了确定功能,我已经到了
\[attribute\]\r?\n(.*)void(.*)\r?\n.*\{\r?\n([^\{\}]*)\}
但这仅适用于不包含由大括号分隔的任何其他代码块的函数。如果我将最后一个捕获组设置为[\s\S]
(所有字符),它只会选择从第一个函数的开头到最后一个函数结尾的所有文本。有没有办法绕过这个并选择一个完整的函数?
答案 0 :(得分:1)
I am afraid balancing constructs themselves are not enough since you may have unbalanced number of them in the method body. You can still try this regex that will handle most of the caveats:
\[attribute\](?<signature>[^{]*)(?<body>(?:\{[^}]*\}|//.*\r?\n|"[^"]*"|[\S\s])*?\{(?:\{[^}]*\}|//.*\r?\n|"[^"]*"|[\S\s])*?)\}
The regex will ignore all {
and }
in the string literals and //
-like comments, and will consume {...}
blocks. The only thing it does not support is /*...*/
multiline comments. Please let me know if you also need to account for them.
答案 1 :(得分:0)
坏消息是,您无法通过“搜索和替换”功能执行此操作,因为它不支持平衡组。您可以在C#中编写一个单独的程序,为您完成。
获得匹配右括号的构造是:
(?=\{)(?:(?<open>\{)|(?<-open>\})|[^\{\}])+?(?(open)(?!))
匹配{...}
的块。但正如@DmitryBychenko所说,它不尊重评论或字符串。