Extracting string between : and next whitespace

Viewed 60

I am trying to extract the parameter variables :country and :age from this statement and store them in a string[] or List or something like that. But what is the easiest way to do that? Regex? String-Methods?

string sql = "select firstname, age, country from Table where country = :country and age > :age order by age";

My approach so far :

string[] sub = sql.Split(' ');
        List<string> parameter = new List<string>();

        for (int i = 0; i < sub.Length; i++)
        {
            if (sub[i].StartsWith(':'))
            {
                parameter.Add(sub[i]);
            }
        }    //
1 Answers

Have you considered using Regular Expression?

public static void FindMatches()
{
    string text = "select firstname, age, country from Table where country = :country and age > :age order by age";
    Regex regex = new Regex(@":\w+", RegexOptions.IgnoreCase);

    MatchCollection matches = regex.Matches(text);

    foreach (Match match in matches)
    {
        Console.WriteLine(match.Value);
    }
}

Outputs:

:country
:age

: will match the colon character
\w will match word boundary (alphanumeric and underscore)
+ match 1 or more the preceding token

Related