5tar-Kaster
5tar-Kaster

Reputation: 908

using regex to find methods in C# code files

I have like 30 C# class files that all have the a method with the same name but not the same code inside, I want to change this by searching the C# file for a regex match of the method and whatever is inside. So far my regex can find the first line of the method (thats the easy part) but I cannot figure out how to find the opening curly brace and the closing curly brace with uknown number of characters in between.

Here is my attempt but I'm no expert

private void btnDelete_Click\(object sender, EventArgs e\)
\{
\S
\}

And this is the method I need to find

    private void btnDelete_Click(object sender, EventArgs e)
    {
        if (gridView1.RowCount <= 0) return;

        this.rowHandle = gridView1.FocusedRowHandle;
        currentState = state.delete;

        MessageResult res = new Global.sysMessages.sysMessagesClass().viewMessage(
            MessageType.Warning,
            "Delete Warning",
            "You are about to delete this record from the system forever.\nare you sure you want to continue?",
            ButtonTypes.YesNo,
            MessageDisplayType.Small);

        if (res == MessageResult.Yes)
        {
            delete(rowHandle);
            loadGrid();
        }
        currentState = state.idle;
    }

Any help is welcome, Thanks

Upvotes: 4

Views: 2668

Answers (3)

user489998
user489998

Reputation: 4521

If the method isn't at the end of the file and you know the scope of the following method (in this example "private"), you could just use

void btnDelete_Click(.|\n)*(?=private)

Upvotes: -1

gwillie
gwillie

Reputation: 1899

Try this :)

\s*private\svoid\sbtnDelete_Click\(.*?\)\s*\{.+?\}(?!['"].*\}.*['"].*)

Don't forgot the DOTALL, ie . matches everything including \n.

Everything between \{.+?\} is the method's code.

UPDATE:

As pointed out, the above regex will fail, so here is a recursive that seems to do the trick:

{(?:[^{}]+|(?R))*}

Also, it will fail if there are } inside string vars, something I'm looking into as using parsers for simple jobs can be overkill sometimes :)

Upvotes: 1

Stephan
Stephan

Reputation: 43013

Solution

private\s+void\s+btnDelete_Click\s*\(object\s+sender,\s*EventArgs\s+e\)\s*\{.+;\s+\}\s*

Regular expression visualization

Demo

Here

Discussion

The central problem is how to match the final curly brace. I assume that the btnDelete_Click method is not placed at the end of the class. Otherwise, this regex is useless.

This regex can be used for quick and dirty work that has a one-time use life span.

Upvotes: 1

Related Questions