String tokenizer via UDF I am trying to implement strings tokenizer in Excel via UDF using C# and Excel-Dna. Personally I found the mIRC's function $gettok pretty useful due to the lack of string functions in Excel.

Examples

getTok("Aquel que no espera vencer ya esta vencido",   1, 32) -&gt; "Aquel"
getTok("Aquel que no espera vencer ya esta vencido",  -1, 32) -&gt; "vencido"
getTok("Aquel que no espera vencer ya esta vencido", 2-4, 32) -&gt; "que no espera"
getTok("Aquel que no espera vencer ya esta vencido",   0, 32) -&gt; "Aquel que no espera vencer ya esta vencido"


Code

[ExcelFunction(Category="String Utilities", Name = "getTok")]
public static string getTok(string text, string token, int delimiter)
{
    int from = 0;
    int to = 0;

    string tokenPatter = @"(\d+)(-)(\d+)?";
    string[] tokens = text.Split(new char[] { (char)delimiter });

    Regex tokenRegex = new Regex(tokenPatter, RegexOptions.IgnoreCase);
    Match tokenMatch = tokenRegex.Match(token);

    if (tokenMatch.Success)
    {
        StringBuilder sb = new StringBuilder();
        from = short.Parse(tokenMatch.Groups[0].Value);

        if (tokenMatch.Groups.Count == 1) to = from;
        else if (tokenMatch.Groups.Count == 2) to = (short)tokens.Length;
        else to = short.Parse(tokenMatch.Groups[2].Value);

        for (int i = from; i &lt;= to; i++)
        {
            sb.Append(tokens[i - 1] + ((char)delimiter));
        }

        return sb.ToString();
    }

    int index = int.Parse(token);
    if (index &gt; 0) return tokens[index - 1];
    else return tokens[tokens.Length + index];    
}


Questions


What would you improve on?
Have you tried something similar with Excel?
In this statement:

for (int i = from; i &lt;= to; i++)
    {
        sb.Append(tokens[i - 1] + ((char)delimiter));
    }


The way that you have it written, I don't think that i will ever hit to.

Also, I would change some variable names to make it more readable. from and to got confusing, I had to keep telling myself that those are variables.  I recommend doing something like:

int intFrom;
int intTo;


at the very least, so that you automatically know that those are integer variables. 

Also you have an int for a delimiter? Why not just pass a char as a delimiter?

Other than that I think the code looks good.