Last active
June 6, 2019 02:45
-
-
Save ck3g/d735c0ea50c228144a18cd2915e9ddd0 to your computer and use it in GitHub Desktop.
Example of how to capture group values using Regular expressions in Swift http://whatdidilearn.info/2018/07/29/how-to-capture-regex-group-values-in-swift.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct FilmSeries { | |
var title: String | |
var season: Int? | |
var episode: Int? | |
} | |
var series = [ | |
FilmSeries(title: "Pilot", season: 1, episode: 1), | |
FilmSeries(title: "The Party", season: 1, episode: 2), | |
FilmSeries(title: "Season 1 Episode 3 - When Joey meets Zoey", season: nil, episode: nil) | |
] | |
func findSeasonAndEpisodeFrom(title: String) -> (Int?, Int?) { | |
var seasonNumber: Int? | |
var episodeNumber: Int? | |
let pattern = "^Season\\s+(?<season>\\d+)\\s+Episode\\s+(?<episode>\\d+)" | |
let regex = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) | |
if let match = regex?.firstMatch(in: title, options: [], range: NSRange(location: 0, length: title.utf16.count)) { | |
if let seasonRange = Range(match.range(withName: "season"), in: title) { | |
seasonNumber = Int(title[seasonRange]) | |
} | |
if let episodeRange = Range(match.range(withName: "episode"), in: title) { | |
episodeNumber = Int(title[episodeRange]) | |
} | |
} | |
return (seasonNumber, episodeNumber) | |
} | |
findSeasonAndEpisodeFrom(title: "Season 1 Episode 3 - When Joey meets Zoey") | |
findSeasonAndEpisodeFrom(title: "Season 1 - When Joey meets Zoey") | |
findSeasonAndEpisodeFrom(title: "Episode 3 - When Joey meets Zoey") | |
findSeasonAndEpisodeFrom(title: "When Joey meets Zoey") | |
let updartedSeries = series.map { (series: FilmSeries) -> FilmSeries in | |
if series.season == nil { | |
let (season, episode) = findSeasonAndEpisodeFrom(title: series.title) | |
return FilmSeries(title: series.title, season: season, episode: episode) | |
} | |
return series | |
} | |
updartedSeries |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment