using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; namespace Emby.Naming.Video { /// /// . /// public static class CleanStringParser { /// /// Attempts to extract clean name with regular expressions. /// /// Name of file. /// List of regex to parse name and year from. /// Parsing result string. /// True if parsing was successful. public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList expressions, out ReadOnlySpan newName) { if (string.IsNullOrEmpty(name)) { newName = ReadOnlySpan.Empty; return false; } // Iteratively apply the regexps to clean the string. bool cleaned = false; for (int i = 0; i < expressions.Count; i++) { if (TryClean(name, expressions[i], out newName)) { cleaned = true; name = newName.ToString(); } } newName = cleaned ? name.AsSpan() : ReadOnlySpan.Empty; return cleaned; } private static bool TryClean(string name, Regex expression, out ReadOnlySpan newName) { var match = expression.Match(name); int index = match.Index; if (match.Success) { var found = match.Groups.TryGetValue("cleaned", out var cleaned); if (!found || cleaned == null) { newName = ReadOnlySpan.Empty; return false; } newName = name.AsSpan().Slice(cleaned.Index, cleaned.Length); return true; } newName = ReadOnlySpan.Empty; return false; } } }