import Foundation
let pattern = #"""
(?(DEFINE)
(?<int>
(?:
\G|
(?!\n)
)
\s*\b\d{1,5}\s*
)
(?<timepart>
(
s|
m|
h|
d
)
\b
)
)
^
((?&int))
((?&timepart))
(?<string>.+)
$
"""#
let regex = try! NSRegularExpression(pattern: pattern, options: [.anchorsMatchLines, .caseInsensitive, .allowCommentsAndWhitespace])
let testString = #"""
2min baz
12 mins foo
1 hour 20 mins remind this
1sec
5 hours
1 sec foo
3 minutes 4 seconds
3333 sec do
1 hrs 20 mins 5 seconds remind this
2 days 3 hrs 20 mins 5 seconds remind this
foo 2sec bar //fail
2 s hi
3 m foo
3m bar
2d baz
9 h foobar
"""#
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