Refactor TryParseMention function to use regexes

This commit is contained in:
Ske 2020-05-02 15:43:07 +02:00
parent cad5b71f14
commit 3fd89c1a45

View File

@ -8,6 +8,7 @@ namespace PluralKit.Bot
{ {
public static class StringUtils public static class StringUtils
{ {
private static readonly Regex USER_MENTION = new Regex("^<@!?(\\d{17,19})>$");
public static DiscordColor? ToDiscordColor(this string color) public static DiscordColor? ToDiscordColor(this string color)
{ {
if (int.TryParse(color, NumberStyles.HexNumber, null, out var colorInt)) if (int.TryParse(color, NumberStyles.HexNumber, null, out var colorInt))
@ -32,18 +33,14 @@ namespace PluralKit.Bot
public static bool TryParseMention(this string potentialMention, out ulong id) public static bool TryParseMention(this string potentialMention, out ulong id)
{ {
if (ulong.TryParse(potentialMention, out id)) return true; if (ulong.TryParse(potentialMention, out id)) return true;
// Roughly ported from Discord.MentionUtils.TryParseUser var match = USER_MENTION.Match(potentialMention);
if (potentialMention.Length >= 3 && potentialMention[0] == '<' && potentialMention[1] == '@' && potentialMention[potentialMention.Length - 1] == '>') if (match.Success)
{ {
if (potentialMention.Length >= 4 && potentialMention[2] == '!') id = ulong.Parse(match.Groups[1].Value, NumberStyles.None, CultureInfo.InvariantCulture);
potentialMention = potentialMention.Substring(3, potentialMention.Length - 4); //<@!123> return true;
else
potentialMention = potentialMention.Substring(2, potentialMention.Length - 3); //<@123>
if (ulong.TryParse(potentialMention, NumberStyles.None, CultureInfo.InvariantCulture, out id))
return true;
} }
return false; return false;
} }