aboutsummaryrefslogtreecommitdiff
path: root/Emby.Naming/Video/CleanStringParser.cs
blob: a336f8fbd18db188b5a327a199a243757ff99e4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;

namespace Emby.Naming.Video
{
    /// <summary>
    /// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
    /// </summary>
    public static class CleanStringParser
    {
        /// <summary>
        /// Attempts to extract clean name with regular expressions.
        /// </summary>
        /// <param name="name">Name of file.</param>
        /// <param name="expressions">List of regex to parse name and year from.</param>
        /// <param name="newName">Parsing result string.</param>
        /// <returns>True if parsing was successful.</returns>
        public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList<Regex> expressions, out string newName)
        {
            if (string.IsNullOrEmpty(name))
            {
                newName = string.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;
                }
            }

            newName = cleaned ? name : string.Empty;
            return cleaned;
        }

        private static bool TryClean(string name, Regex expression, out string newName)
        {
            var match = expression.Match(name);
            if (match.Success && match.Groups.TryGetValue("cleaned", out var cleaned))
            {
                newName = cleaned.Value;
                return true;
            }

            newName = string.Empty;
            return false;
        }
    }
}