0

Right now I have this to find a method

def getMethod(text, a, filetype):
    start = a
    fin = a
    if filetype == "cs":
        for x in range(a, 0, -1):
            if text[x] == "{":
                start = x
                break
        for x in range(a, len(text)):
            if text[x] == "}":
                fin = x
                break
    return text[start:fin + 1]

How can I get the method the index a is in?

I can't just find { and } because you can have things like new { } which won't work

if I had a file with a few methods and I wanted to find what method the index of x is in then I want the body of that method for example if I had the file

private string x(){
    return "x";
}

private string b(){
    return "b";
}

private string z(){
    return "z";
}

private string a(){
    var n = new {l = "l"};
    return "a";
}

And I got the index of "a" which lets say is 100

then I want to find the body of that method. So everything within { and }

So this...

{
    var n = new {l = "l"};
    return "a";
}

But using what I have now it would return:

                {l = "l"};
    return "a";
}
congusbongus
  • 13,359
  • 7
  • 71
  • 99
FabianCook
  • 20,269
  • 16
  • 67
  • 115
  • Can you give an example of what you're trying to match? There is not enough context to your question. What kind of "methods" are these, and what are you searching in? – Celada Feb 25 '13 at 00:47
  • There you go. I think that explains it a bit more. – FabianCook Feb 25 '13 at 01:31

2 Answers2

1

If my interpretation is correct, it seems you are attempting to parse C# source code to find the C# method that includes a given position a in a .cs file, the content of which is contained in text.

Unfortunately, if you want to do a complete and accurate job, I think you would need a full C# parser.

If that sounds like too much work, I'd think about using a version of ctags that is compatible with C# to generate a tag file and then search in the tag file for the method that applies to a given source file line instead of the original source file.

Community
  • 1
  • 1
Simon
  • 10,679
  • 1
  • 30
  • 44
1

As Simon stated, if your problem is to parse source code, the best bet is to get a proper parser for that language.

If you're just looking to match up the braces however, there is a well-known algorithm for that: Python parsing bracketed blocks

Just be aware that since source code is a complex beast, don't expect this to work 100%.

Community
  • 1
  • 1
congusbongus
  • 13,359
  • 7
  • 71
  • 99