import Foundation
let pattern = #"^\w+(\s\w&\w)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
Employee Communications & Engagement, WB
SVP of Global Insights & Analytics, WB
SVP of Nonfiction, HBO Max
VP of Talent Relations and Development, TCM
Global Franchise Management, DC
WB Technology Group
President, EMEA & APAC
SVP & CFO, EMEA & APAC
Director, Service Delivery
SVP for Sales and Client Partnerships, Legacy Turner
Technical Director, WarnerMedia
Dir. of Brand Distribution, WarnerMedia
Dir. Strategic & Consumer Insights, Turner Sports
Manager for Digital Asset & Photo Library, Brand Experience
Creative Manager for Creative Services, Cartoon Network
// 2 words
Cincinnati Bearcats
Miami (FL) Hurricanes
Miami (OH) Redhawks
// three words
South Florida Bulls // 2.1
Saint Joseph's Hawks
Duke Blue Devils // 1.2
UNLV Runnin' Rebels // with apostrophe
// 4 words
North Carolina Tar Heels
Notre Dame Fighting Irish
St John's Red Storm
Florida A&M Rattlers
William & Mary Tribe
St Francis (PA) Red Flash
"""#
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