Created
August 17, 2012 10:54
-
-
Save aliostad/3377922 to your computer and use it in GitHub Desktop.
Parses commandline into name value pairs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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