import Foundation
let pattern = #"all"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
A regex with the character pattern "all", will match each occurrences of the letter a followed by two l letters in a text. This means it will find matches for all, hallway, ballon and fall.
The two l:s, needs to come after the letter a, so it will not match dollar or pillar. The regex also expects two l:s, one isn't enough. It will not find any match in words like falcon or although. If the text contains other characters in betwen the a and the two l:s, it won't consider it as a match. This means it won't find a match in the name Al Leaong or if we misspell all life as al life.
"""#
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