Search code examples
c#regexvisual-studiodecompiler

Regex to restore VisualStudio Designer Code


I have a C# project recovered from a decompiled VisualStudio project. I am trying to restore the .Designer.cs files but the formatting of the code in the decompiled files do not match the format that VisualStudio expects.

In particular I need to remove the use of the tempory variables. I am looking for a Regex expression that I can use in VisualStudio to do a search and replace to reformat the following type of code:

Replace:

Label label1 = this.Label1;  
Point point = new Point(9, 6);  
label1.Location = point;  

With:

this.Label1.Location = new Point(9, 6);  

Replace:

TextBox textBox5 = this.txtYear;  
size = new System.Drawing.Size(59, 20);  
textBox5.Size = size;  

With:

this.txtYear.Size = new System.Drawing.Size(59, 20);  

etc.


Solution

  • Here’s a regex replacement that works for the two examples you gave. I confirmed that it does the expected modifications in this online .NET regex tester.

    You will probably have to modify this regex further to suit your needs. For one thing, I am not sure how varied the code is within your file. If there is “normal” C# code mixed in with those three-line snippets, then this regex will just mess them up. You also didn’t specify how those three-line snippets are separated in the file, so you will have to edit the regex so it can find the start of the three-line snippet. For example, if all three-line snippets began with two Windows-format newlines, you could add \r\n\r\n to the start of the regex to detect those, and to the start of the replacement so they are preserved.

    Find regex

    [^=]+=\s*([^;]+);\s*\n[^=]+=\s*([^;]+);\s*\n\w+(\.[^=]+=\s*)\w+;
    

    Version with whitespace and comments:

    [^=]+=\s*      # up to the = of the first line
    ([^;]+)        # first match: everything until…
    ;\s*\n         # the semicolon and end of the first line
    
    [^=]+=\s*      # up to the = of the second line
    ([^;]+)        # second match: everything until…
    ;\s*\n         # the semicolon and end of the second line
    
    \w+            # variable name (assumed to be the first line)
    (\.[^=]+=\s*)  # third match: “.propertyName = ”
    \w+            # variable name (assumed to be the second line)
    ;              # semicolon at the end of the line
    

    Replacement string

    $1$3$2;
    

    That adds up to the first line after the equal sign, then .propertyName =, then the second line after the equal sign, then an ending semicolon.