Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Example of how to capture group values using Regular expressions in Swift
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: 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.