Nice regex to parse stored procedure call

9 November 2006
I recently needed to parse a line of text which represents a stored procedure call to a database.
The format is
databaseName#storedProcedureName @parameterName=parameterValue

in .Net I used the named groups in my regular expression to get the parts:

^(?<database>[a-z]+)#(?<sproc>[a-z_0-9]+)( (?<parametername>@[a-z_0-9]+)=(?<parametervalue>[a-z_0-9']+))?

Database and stored procedure name are mandatory, then optionally separated by a space a single parameter.


   RegexOptions options = RegexOptions.IgnoreCase;
Regex regex = new Regex(@"^(?[a-z]+)#(?[a-z_0-9]+)( (?@[a-z_0-9]+)=(?[a-z_0-9']+))?", options);

Match match = regex.Match(sprocCall);

if (match.Groups.Count == 6)
{
// we always expect six groups
// if not the string format was not correct
string database = match.Groups["database"].Value;
string sprocName = match.Groups["sproc"].Value;
string parameterName = match.Groups["parametername"].Value.Trim();
string parameterValue = match.Groups["parametervalue"].Value.Trim();
// use the components to make a database call
}

Pages in this section

Categories

ASP.Net | Community | Development | IIS | IT Pro | Security | SQL (Server) | Tools | Web | Work on the road | Windows