import Foundation
let pattern = #"Match all movie titles containing a word end in 'tes'"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
Enemy at the Gates
First Love, Last Rites
BrĂ¼no
30 Minutes or Less
The Ice Pirates
The Mighty Macs
Bridget Jones: The Edge of Reason
Blood Diamond
50 First Dates
The Greatest Game Ever Played
The Pirates! Band of Misfits
The World's Fastest Indian
Van Wilder: Party Liaison
200 Cigarettes
Midnight in Paris
The Greatest Story Ever Told
Kites
The Pirates Who Don't Do Anything: A VeggieTales Movie
Notes on a Scandal
Pirates of the Caribbean: The Curse of the Black Pearl
88 Minutes
The Ladykillers
The Greatest Movie Ever Sold
Pirates of the Caribbean: On Stranger Tides
Bangkok Dangerous
ATL
90 Minutes in Heaven
The Greatest Show on Earth
The Sweetest Thing
Beastmaster 2: Through the Portal of Time
From Dusk Till Dawn
The White Countess
Olympus Has Fallen
Akira
Bend It Like Beckham
The Art of Getting By
World's Greatest Dad
The Greatest
Irreplaceable
Gridiron Gang
20 Dates
Romance & Cigarettes
Pirates of the Caribbean: At World's End
Dick Tracy
Bathory: Countess of Blood
The Cure
15 Minutes
The Past is a Grotesque Animal
Pirates of the Caribbean: Dead Man's Chest
Surrogates
Sleep Tight
"""#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let matches = regex.matches(in: testString, range: stringRange)
var result: [[String]] = []
for match in matches {
var groups: [String] = []
for rangeIndex in 1 ..< match.numberOfRanges {
let nsRange = match.range(at: rangeIndex)
guard !NSEqualRanges(nsRange, NSMakeRange(NSNotFound, 0)) else { continue }
let string = (testString as NSString).substring(with: nsRange)
groups.append(string)
}
if !groups.isEmpty {
result.append(groups)
}
}
print(result)
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Swift 5.2, please visit: https://developer.apple.com/documentation/foundation/nsregularexpression