CleanStringParser.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System.Collections.Generic;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Text.RegularExpressions;
  4. namespace Emby.Naming.Video
  5. {
  6. /// <summary>
  7. /// <see href="http://kodi.wiki/view/Advancedsettings.xml#video" />.
  8. /// </summary>
  9. public static class CleanStringParser
  10. {
  11. /// <summary>
  12. /// Attempts to extract clean name with regular expressions.
  13. /// </summary>
  14. /// <param name="name">Name of file.</param>
  15. /// <param name="expressions">List of regex to parse name and year from.</param>
  16. /// <param name="newName">Parsing result string.</param>
  17. /// <returns>True if parsing was successful.</returns>
  18. public static bool TryClean([NotNullWhen(true)] string? name, IReadOnlyList<Regex> expressions, out string newName)
  19. {
  20. if (string.IsNullOrEmpty(name))
  21. {
  22. newName = string.Empty;
  23. return false;
  24. }
  25. // Iteratively apply the regexps to clean the string.
  26. bool cleaned = false;
  27. for (int i = 0; i < expressions.Count; i++)
  28. {
  29. if (TryClean(name, expressions[i], out newName))
  30. {
  31. cleaned = true;
  32. name = newName;
  33. }
  34. }
  35. newName = cleaned ? name : string.Empty;
  36. return cleaned;
  37. }
  38. private static bool TryClean(string name, Regex expression, out string newName)
  39. {
  40. var match = expression.Match(name);
  41. if (match.Success && match.Groups.TryGetValue("cleaned", out var cleaned))
  42. {
  43. newName = cleaned.Value;
  44. return true;
  45. }
  46. newName = string.Empty;
  47. return false;
  48. }
  49. }
  50. }