2

I need to find all functions in my VS solution with a certain attribute and insert a line of code at the end and at the beginning of each one. For identifying the functions, I've got as far as

\[attribute\]\r?\n(.*)void(.*)\r?\n.*\{\r?\n([^\{\}]*)\}

But that only works on functions that don't contain any other blocks of code delimited by braces. If I set the last capturing group to [\s\S] (all characters), it simply selects all text from the start of the first function to the end of the last one. Is there a way to get around this and select just one whole function?

2
  • 1
    What if a function is commeted out, e.g. // void DoIt() or /* void DoIt() */. Other possibility if "function" is a part of a string, e.g. String St = "void DoIt() {return;}"; Use parser, RegEx is not enough Commented Jun 26, 2015 at 8:56
  • Wouldn't it be better to use assembly weaving instead? Like writing a Fody plugin? Commented Jun 26, 2015 at 9:27

2 Answers 2

2

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])*?)\}

See demo on RegexStorm

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.

enter image description here

Sign up to request clarification or add additional context in comments.

10 Comments

Am I doing something wrong? Your demo shows 0 results for me, both on your own example and if I feed it some of my own code.
I do not know why you get 0 results, I have pasted the result table into the answer.
@Jammer Show your code with a test case via any code sharing site, and I'll be glad to show where it goes wrong.
@SiddhiDilipKamat If you mean how to run the regex search in C#, Jammer has posted a [link in the comment.
@SiddhiDilipKamat I doubt that. You should dig in the direction of Resharper.
|
0

The bad news is that you can't do that by the Search-And-Replace feature because it doesn't support balancing groups. You can write a separate program in C# that does it for you.

The construct to get the matching closing brace is:

(?=\{)(?:(?<open>\{)|(?<-open>\})|[^\{\}])+?(?(open)(?!))

This matches a block of {...}. But as @DmitryBychenko mentioned it doesn't respect comments or strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.