A NuGet package. It aim is to help you write extendable and command-based console programs in C# and .Net. https://www.craigoates.net/Software/Project/7
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
2.4 KiB

using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Console.Waterworks.Models
{
class Command
{
public string Name { get; set; }
public string ClassName { get; set; }
private List<string> _arguments;
public IEnumerable<string> Arguments
{
get
{
return _arguments;
}
}
public Command(string input, string commandsNamespace, string className)
{
// Ugly regex to split string on spaces, but preserve quoted text intact:
var stringArray =
Regex.Split(input, "(?<=^[^\"]*(?:\"[^\"]*\"[^\"]*)*) (?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
_arguments = new List<string>();
for (int i = 0; i < stringArray.Length; i++)
{
// The first element is always the command:
if (i == 0)
{
Name = stringArray[i];
// Set the class name
ClassName = className;
string[] s = stringArray[0].Split('.');
if (s.Length == 2)
{
ClassName = s[0];
Name = s[1];
}
}
else
{
var inputArgument = stringArray[i];
// Assume that most of the time, the input argument is NOT quoted text:
string argument = inputArgument;
// Is the argument a quoted text string?
var regex = new Regex("\"(.*?)\"", RegexOptions.Singleline);
var match = regex.Match(inputArgument);
// If it IS quoted, there will be at least one capture:
if (match.Captures.Count > 0)
{
// Get the unquoted text from within the qoutes:
var captureQuotedText = new Regex("[^\"]*[^\"]");
var quoted = captureQuotedText.Match(match.Captures[0].Value);
// The argument should include all text from between the quotes
// as a single string:
argument = quoted.Captures[0].Value;
}
_arguments.Add(argument);
}
}
}
}
}