CleanStringParser.cs 1.8 KB

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