From 204d2a475dad7d746625f2a24b6a327e3d97b610 Mon Sep 17 00:00:00 2001 From: Austin Noska Date: Thu, 18 Feb 2021 16:22:16 -0500 Subject: [PATCH] feat: Add MatchAny util method to RegexUtils that tries to match an input against a sequence of patterns. --- ICD.Common.Utils/RegexUtils.cs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/ICD.Common.Utils/RegexUtils.cs b/ICD.Common.Utils/RegexUtils.cs index 0db86a2..f2ea42b 100644 --- a/ICD.Common.Utils/RegexUtils.cs +++ b/ICD.Common.Utils/RegexUtils.cs @@ -1,7 +1,9 @@ using System; +using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; +using ICD.Common.Properties; namespace ICD.Common.Utils { @@ -111,5 +113,34 @@ namespace ICD.Common.Utils return Regex.Replace(input, pattern, evaluator, options); } + + /// + /// Returns the first successful match or the last failure. + /// + /// + /// + /// + [NotNull] + public static Match MatchAny([NotNull] string input, [NotNull] IEnumerable patterns) + { + if (input == null) + throw new ArgumentNullException("input"); + + if (patterns == null) + throw new ArgumentNullException("patterns"); + + Match last = null; + foreach (string pattern in patterns) + { + last = Regex.Match(input, pattern); + if (last.Success) + break; + } + + if (last == null) + throw new InvalidOperationException("No patterns provided"); + + return last; + } } }