Reputation: 604
I have a function in C# that finds the name of a function in a source file such as
function void MyFunc
I'm trying to create a substring that starts after "void " and I need to find the length of the name of the function. There will always be a space or a newline after the function name.
module MyApplication
[EntryPoint]
function void main
write("a string")
endfunction
endmodule
Upvotes: 1
Views: 115
Reputation: 31877
Sprache can do this, but you'd need to write a grammar for the whole file, as it doesn't implement "searching" for a match.
Something along these lines would parse just the function declaration - as noted above, to make your scenario work you need to add rules for modules and so on.
var identifier = (from first in Parse.Letter
from rest in Parse.LetterOrDigit.Many().Text()
select first + rest).Token();
var returnType = Parse.String("void").Or(Parse.String("int")).Token();
var functionKeyword = Parse.String("function").Token();
var endFunctionKeyword = Parse.String("endfunction").Token();
var function = from fk in functionKeyword
from rt in returnType
from functionName in identifier
from body in Parse.AnyChar.Until(endFunctionKeyword)
select functionName;
var name = function.Parse("function void main write(\"a string\") endfunction");
The variable name
above will contain the string "main"
(unless I've made some typos :))
Sprache is a bit more powerful than regular expressions, but doesn't require any special build-time processing. There are some tutorials on this approach linked from the Sprache homepage.
Upvotes: 0
Reputation: 12468
That's "crying for using regex". Try this:
Regex regex = new Regex("(function void ){1,1}(?<functionName>^\w*)");
Upvotes: 0
Reputation: 134125
I assume that the function name might have other stuff after it, like a parameter list.
What you want to do is look for the word "void", go past it, find the first non-space character (which is the beginning of the function name), and then go to the next space or end of line.
You can use:
const string LookFor = "void "; // note space at end.
string GetFunctionName(string line)
{
int voidPos = line.IndexOf(LookFor);
if (voidPos == -1)
return null;
int functionStart = voidPos + LookFor.Length;
int spacePos = line.IndexOf(' ', functionStart);
if (spacePos == -1)
spacePos = line.Length;
return line.Substring(functionStart, spacePos - functionStart);
}
Upvotes: 1
Reputation: 56779
You can use LastIndexOf
to find the last space, and grab the part of the string following to get the function name. Then use the Length
property to get the length of the code:
var s = "function void MyFunc "; // example string
var s2 = s.Trim(); // remove any extra spaces at the end
var funcName = s2.Substring(s2.LastIndexOf(' ') + 1); // 'MyFunc'
var length = funcName.Length; // 6
Demo: http://www.ideone.com/64IYz
Upvotes: 1