0

I'm trying to regex search for += operator matches inside a function named OnDisabled() in Rider (JetBrains).

Regex I have so far: /OnDisable \(.*?\) \{(?=.*?)[^{}]+\}/gm but it matches everything inside the curly brackets right now.

Example code I have for testing is as follows:

private void OnEnable () {
  someEvent.OnEventRaised += MyFunction; // Ignored
  someOtherEvent.OnEventRaised += MyFunction2; // Ignored
  anotherEvent.OnEventRaised += MyFunction3; // Ignored
}

private void OnDisable () {
  someEvent.OnEventRaised += MyFunction; // <-- Should be found #1
  someOtherEvent.OnEventRaised -= MyFunction2; // Ignored
  anotherEvent.OnEventRaised += MyFunction3; // <-- Should also be found #2
}

Additional information:

  1. Function/code style is always OnDisable () {
  2. Indentation can vary inside the function
  3. Only want to find any += operator inside the function, rest is not important
Saucy
  • 165
  • 1
  • 11
  • 1
    Regex is not a suitable tool for this task. It's not trivial finding out where the method ends. Using `[^{}]+` will have false-negatives (imagine having something like `var arr = new[] { 1 };` in the body of the method) and even writing something for matching balanced curly brackets will struggle with curly brackets inside strings. You should probably write a parser instead. – 41686d6564 stands w. Palestine Aug 03 '22 at 10:55
  • Parsing C# using a Regex will in general not work. It is already difficult to find the end of the method (counting braces). string literals and comments will make it impossible. – Klaus Gütter Aug 03 '22 at 10:55
  • 2
    If you want to look for these things in your own code, it may be easier to do it with [Roslyn](https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/) instead - the parsing and analysis layer of the C# compiler, which can be used as a library. [Here's an example for how to look for event handler subscriptions](https://stackoverflow.com/questions/54324943/c-sharp-how-can-i-detect-evenhandler-subscription-in-roslyn) (ie what `+=` represents). – Jesper Aug 03 '22 at 11:29

0 Answers0