Skip to content

Instantly share code, notes, and snippets.

@aliostad
Created August 17, 2012 10:54
Show Gist options
  • Save aliostad/3377922 to your computer and use it in GitHub Desktop.
Save aliostad/3377922 to your computer and use it in GitHub Desktop.
Parses commandline into name value pairs
/// <summary>
/// Parses commandline parameters that are in format of
/// -name:value
/// /name=value
/// -name="value 1"
/// </summary>
public static class CommandLineParser
{
private const string CommandLinePattern =
"\\s+[-/](?<name>\\w+)[=:](?:(?<value>[^\\s\\:\"]+)|(?:\"(?<value>.*)\"))";
private static readonly Regex _parser = new Regex(CommandLinePattern);
public static NameValueCollection Parse(string commandLine)
{
if (commandLine == null)
throw new ArgumentNullException("commandLine");
var nameValueCollection = new NameValueCollection();
Parse(commandLine, nameValueCollection);
return nameValueCollection;
}
public static NameValueCollection Parse(string[] args)
{
var nameValueCollection = new NameValueCollection();
foreach (var s in args)
{
Parse(s, nameValueCollection);
}
return nameValueCollection;
}
private static void Parse(string arg, NameValueCollection nvc)
{
if (!arg.StartsWith(" "))
arg = " " + arg;
var matchCollection = _parser.Matches(arg);
foreach (Match match in matchCollection)
{
nvc.Add(match.Groups[1].Value, match.Groups[2].Value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment