Skip to content

Instantly share code, notes, and snippets.

@harboe
Last active December 18, 2015 09:39
Show Gist options
  • Save harboe/5763294 to your computer and use it in GitHub Desktop.
Save harboe/5763294 to your computer and use it in GitHub Desktop.
A simple console argument parser.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
public static class ArgumentParser
{
#region Field Members
static readonly Regex _splitter = new Regex(
@"^-{1,2}|^/|=|:", RegexOptions.IgnoreCase | RegexOptions.Compiled
);
static readonly Regex _remover = new Regex(
@"^['""]?(.*?)['""]?$", RegexOptions.IgnoreCase | RegexOptions.Compiled
);
#endregion
#region Method Members
// Valid parameters forms:
// {-,/,--}param{ ,=,:}((",')value(",'))
//
// Examples:
// -param1 value1 --param2 /param3:"Test-:-work" /param4=happy
public static NameValueCollection Parse(params string[] args)
{
var arguments = new NameValueCollection();
if (args == null)
return arguments;
string param = null;
string[] parts;
foreach(var txt in args)
{
// Look for new parameters (-,/ or --) and a
// possible enclosed value (=,:)
parts = _splitter.Split(txt, 3);
switch(parts.Length) {
// Found a value (for the last parameter found (space separator))
case 1:
FoundParameterValue(param, parts, arguments);
param = null;
break;
// Found just a parameter
case 2:
FoundParameterWithNoValue(param, parts, arguments);
param = string.IsNullOrEmpty(parts[1]) ? null : parts[1];
break;
// Parameter with enclosed value
case 3:
FoundParameterWithValue(param, parts, arguments);
param = null;
break;
}
}
// In case a parameter is still waiting
if (param != null && arguments[param] == null)
arguments[param] = "true";
return arguments;
}
private static void FoundParameterValue(string param, string[] parts, NameValueCollection collection)
{
if (param != null && collection[param] == null)
collection[param] = _remover.Replace(parts[0], "$1");
}
private static void FoundParameterWithNoValue(string param, string[] parts, NameValueCollection collection)
{
// The last parameter is still waiting.
// With no value, set it to true.
if (param != null && collection[param] == null)
collection[param] = "true";
}
private static void FoundParameterWithValue(string param, string[] parts, NameValueCollection collection)
{
// The last parameter is still waiting.
// With no value, set it to true.
if (param != null && collection[param] == null)
collection[param] = "true";
param = parts[1];
// Remove possible enclosing characters (",')
if (collection[param] == null)
collection[param] = _remover.Replace(parts[2], "$1");
}
#endregion
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment