Refactor rename variables from Editor code

I created a custom editor window in Unity that generates scripts with string variables. That all works well, however I would like to have the ability to rename those variables.

All of those variables are listed as strings in my custom editor. From there, I would like to edit them, and then click rename.

So my question is, how would I find all references of a specific variable in all of my scripts, and rename it (Just like Rename does in Visual studio, but do it on my own from another script).

Any ideas how to achieve something like this?

Hello,

This is a complex question. Indeed, there are a lot of cases to think about: what if a string called abc contains the text “abc”, and you want to rename the variable abc to xyz ? Strings have to be handled.

But this is only the first part of the thing. If you have a nested class, you could have the following case:

class Grandmaster
{
    class Nested
    {
        int myInt;
    }

    int myInt;
}

What happens if you rename myInt ? We have two different variables with the same name.

I think [regular expressions][1] are the way to go. With the following code, I am able to match all substrings that contains the name of a specific variable, given they are not in a string (in the parsed code):

string variableName = "myVar";
string regexPattern = "(?<=^([^\"]|\"[^\"]*\")*)" + variableName; // Ugly eh?
Regex regex = new Regex(regexPattern, RegexOptions.Compiled); 

string myScriptCode = "string myVar = \"myVar\"";
Debug.Log(myScriptCode); // Just to see what we parse

Match match = regex.Match(myScriptCode);

for (int i = 0; i < match.Captures.Count; i++)
{
    Debug.Log(match.Captures*.Value);*

}

I suggest you to read about those regular expressions, which are a very powerful tool for text processing like you’re doing. When you execute it, there is only one line that displays a match, because the “myVar” text that is between the quotes is not detected by our regex, which solves our first problem.
Now for the second problem. This is the actual true penible and horrible problem, because you will either have to create a huge text parser, or to do some syntax tree processing, like [Microsoft Roslyn][2] would allow you to do, so that you no more rely on direct text parsing but on a lower level, a bit closer from what the compiler sees.
I cannot provide you some code to solve that, but if your window generates scripts automatically, I don’t think there will be very complicated cases that would require this kind of analysis (I hope at least).
Regards,
troopy28
[1]: Regex Classe (System.Text.RegularExpressions) | Microsoft Learn
[2]: GitHub - dotnet/roslyn: The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.