DeukBot4/DeukBot4/MessageHandlers/CommandHandler/RequestStructure/ParameterMatcher.cs

87 lines
3.1 KiB
C#
Raw Normal View History

2018-03-28 23:34:48 +00:00
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace DeukBot4.MessageHandlers.CommandHandler.RequestStructure
{
public static class ParameterMatcher
{
public enum ParameterType
{
Word,
Number,
Remainder,
2018-03-29 19:57:16 +00:00
User,
Timespan,
2018-03-28 23:34:48 +00:00
}
public static string[] GenerateRegex(Command command)
{
var arr = new string[command.ParameterTypes.Length];
for (var index = 0; index < command.ParameterTypes.Length; index++)
{
var commandParameterType = command.ParameterTypes[index];
var builder = new StringBuilder();
for (var i = 0; i < commandParameterType.Length; i++)
{
var parameterType = commandParameterType[i];
builder.Append(GetParameterRegex(parameterType, i + 1));
}
2018-03-28 23:34:48 +00:00
arr[index] = builder.ToString();
}
return arr;
}
private static string GetParameterRegex(ParameterType type, int index)
2018-03-28 23:34:48 +00:00
{
switch (type)
{
case ParameterType.Word:
return $" *(?<{index}>\\w+)";
2018-03-28 23:34:48 +00:00
case ParameterType.Number:
return $" *(?<{index}>\\d+)(?:$| |\n)";
2018-03-28 23:34:48 +00:00
case ParameterType.Remainder:
return $" *(?<{index}>.*)";
2018-03-29 19:57:16 +00:00
case ParameterType.User:
2018-10-09 15:28:06 +00:00
return $" *(?:<@!*(?<{index}>\\d+)>|(?<{index}>\\d+)|(?<{index}>\\w+)(?:$| |\n))";
case ParameterType.Timespan:
2018-08-13 16:41:59 +00:00
return $" *(?<{index}>\\d+\\.*\\d*[smhd])";
2018-03-28 23:34:48 +00:00
default:
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
}
public static RequestParameter[] GetParameterValues(Command command, string parameterString)
{
for (var index = 0; index < command.ParametersMatchers.Length; index++)
2018-03-28 23:34:48 +00:00
{
var parameterTypes = command.ParameterTypes[index];
var pattern = command.ParametersMatchers[index];
Match matches;
try
{
matches = Regex.Match(parameterString, pattern);
}
catch (Exception e)
{
2018-08-13 16:41:59 +00:00
Logger.Main.LogError(e.ToString());
return command.RequireParameterMatch ? null : new RequestParameter[0];
}
2018-03-28 23:34:48 +00:00
if (matches.Success)
{
var arr = new RequestParameter[matches.Groups.Count - 1];
for (var i = 1; i < matches.Groups.Count; i++)
{
var group = matches.Groups[i];
arr[i - 1] = new RequestParameter(group.Value, parameterTypes[i - 1]);
}
return arr;
2018-03-28 23:34:48 +00:00
}
}
2018-03-30 12:51:38 +00:00
return command.RequireParameterMatch ? null : new RequestParameter[0];
2018-03-28 23:34:48 +00:00
}
}
}