CleanStringParser.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 ReadOnlySpan<char> newName)
  20. {
  21. if (string.IsNullOrEmpty(name))
  22. {
  23. newName = ReadOnlySpan<char>.Empty;
  24. return false;
  25. }
  26. var len = expressions.Count;
  27. for (int i = 0; i < len; i++)
  28. {
  29. if (TryClean(name, expressions[i], out newName))
  30. {
  31. return true;
  32. }
  33. }
  34. newName = ReadOnlySpan<char>.Empty;
  35. return false;
  36. }
  37. private static bool TryClean(string name, Regex expression, out ReadOnlySpan<char> newName)
  38. {
  39. var match = expression.Match(name);
  40. int index = match.Index;
  41. if (match.Success && index != 0)
  42. {
  43. newName = name.AsSpan().Slice(0, match.Index);
  44. return true;
  45. }
  46. newName = ReadOnlySpan<char>.Empty;
  47. return false;
  48. }
  49. }
  50. }