Monday, 12 May 2014

Regular Expression Command Line Arguments Parser



Here's a simple way to extract a list of switch/flags and their parameters from a command line argument in C#.

Regex regex = new Regex(@"(?< switch> -{1,2}\S*)(?:[=:]?|\s+)(?< value> [^-\s].*?)?(?=\s+[-\/]|$)");

string commands = "--switch value1 --switch2 \"c:\\folder 1\\file1.txt\" -switch-3 value-3 --switch4 -switch5";

List< KeyValuePair< string, string> >  matches = (from match in regex.Matches(commands).Cast< match> ()

select new KeyValuePair< string, string> (match.Groups["switch"].Value, match.Groups["value"].Value)).ToList();

foreach (KeyValuePair< string, string>  _match in matches)
{
Response.Write("
switch:" + _match.Key + "  value:" + _match.Value);
}

You can pass in a command with multiple switches such as "-switch" or "--switch":

--switch1 value1 --switch2 "c:\folder 2\file2.txt" -switch-3 value-3 --switch4 -switch5

 the regex will extract the flags along with any optional values and return a list of key-value pairs.

I had looked at a couple of solutions such as http://www.codeproject.com/Articles/3111/C-NET-Command-Line-Arguments-Parser and http://lukasz-lademann.blogspot.co.uk/2013/01/c-command-line-arguments-parser.html but I think this way is a bit simpler and returns better results.

Also, this way allows optional parameters which can contain file paths, you can test here http://regexhero.net/tester/?id=2f4e252d-c89e-4134-8c7c-65c5186b3338