Skip to content

Instantly share code, notes, and snippets.

@markmals
Last active October 14, 2018 06:07
Show Gist options
  • Save markmals/1dada1455b4d41c61a1fc818046ab1d5 to your computer and use it in GitHub Desktop.
Save markmals/1dada1455b4d41c61a1fc818046ab1d5 to your computer and use it in GitHub Desktop.
Format a file name of a video to the correct Plex format
extension String {
var formattedForPlex: String {
var newName = self
// Remove all text at the end
let regexEndText = "\\d{3,4}p.+"
if let range = newName.range(of: regexEndText, options: .regularExpression) {
newName.removeSubrange(range)
}
// Add seperators ( - ) before and after the season/episode.
let regexSeason = "S\\d\\dE\\d\\d"
if let range = newName.range(of: regexSeason, options: .regularExpression) {
// Don't append a trailing dash if there's no relevant text (i.e. episode name)
// after the episode number.
let trailingDash: String = !(
// Are the last two characters of string convertible to an Int?
(Int(newName.suffix(3).dropLast()) != nil) &&
// Is the third to last character an "E" for "Episode Number?"
(newName.suffix(4).first == "E")
) ? " -" : ""
let seasonEpisodeID = newName[range]
newName.replaceSubrange(range, with: "- \(seasonEpisodeID)\(trailingDash)")
}
// Replace all periods with spaces
newName = newName.replacingOccurrences(of: ".", with: " ")
// Trim all extreneous whitespace
return newName.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment