vote buttons
4
17 Jan 2015 by Super Human

Command Line Arguments Parser

Contract
ICommandLineParser
IDictionary<string, string> Parse(string args);
Test Cases
vote buttons
1
Created By K Bonneau
public void SingleArgument_WithHyphen_ShouldReturnNameWithoutHyphen(ICommandLineParser parser) { var result = parser.Parse("-param1 value1"); Assert.IsTrue(result.ContainsKey("param1")); Assert.AreEqual("value1", result["param1"]); }
vote buttons
1
Created By K Bonneau
public void SingleArgument_WithNoValue_ShouldReturnNameWithEmptyStringValue(ICommandLineParser parser) { var result = parser.Parse("-param1"); Assert.IsTrue(result.ContainsKey("param1")); Assert.AreEqual(String.Empty,result["param1"]); }
vote buttons
1
Created By K Bonneau
public void ArgumentsWithSpaces_SurroundedByQuotes_ShouldReturnFullValueWithQuotes(ICommandLineParser parser) { var result = parser.Parse(@"-fileName ""C:\Some Folder With Space\Some File.ext\"""); Assert.IsTrue(result.ContainsKey("fileName")); Assert.AreEqual(@"""C:\Some Folder With Space\Some File.ext\""", result["fileName"]); }
You must be logged in to add test cases

1 Solution

vote buttons
2
0.08
avg time in ms
17 Jan 2015 by Super Human
public class Solution : ICommandLineParser { public IDictionary<string, string> Parse(string commands) { var result = new Dictionary<string, string>(); var regex = new Regex(@"(-{1,2}|/)(?<switch>\S*)(?:[=:]?|\s+)(?<value>[^-\s].*?)?(?=\s+[-\/]|$)"); 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) { result.Add(_match.Key, _match.Value); } return result; } }
Test Case Run Summary
SingleArgument_WithHyphen_ShouldReturnNameWithoutHyphen
SingleArgument_WithNoValue_ShouldReturnNameWithEmptyStringValue
ArgumentsWithSpaces_SurroundedByQuotes_ShouldReturnFullValueWithQuotes
download solution
Try this Solution
Comments