import Foundation
let pattern = #"(?<!\w)\b(?:(?<hour_digit>\d+)(?:\s*(?:more|another))?\s*hours?)?(?:(?:\s*(?:or|up to|and|to))*\s*(?<minute_digit>\d+)(?:\s*(?:more|another))?\s*minutes?)?(?:(?:\s*(?:or|up to|and|to))*\h*(?<second_digit>\d+)(?:\s*(?:more|another))?\s*seconds?)?\b(?!\w)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
1 second
21 seconds
1 minutes
21 minutes
1 hour
11 hours
2 more seconds
1 more second
12 more minutes
21 more hours
11 hours
5 hours 5 minutes to 6 hours 6 minutes
7 hours 7 minutes
9 hours or up to 10 hours
5 hours and 15 minutes
For the first step, wash the clothes for 15 minutes. While the clothes are washing, hold your breath for up to 5 minutes.
"""#
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