import Foundation
let pattern = #"(\d+)\s?°\s?(\d+)\s?'\s?(\d+\.?\,?\d*?)"\s?(N|W|S|E)"#
let regex = try! NSRegularExpression(pattern: pattern, options: .anchorsMatchLines)
let testString = #"""
15° 1' 36.991" E
15° 2' 21.421" E
15° 2' 0.712" E
15° 2' 45.181" E
15° 3' 1.709" E
14° 58' 24.822" E
14° 58' 39.840" E
14° 58' 26.234" E
14° 58' 45.145" E
15° 0' 14.01" E
15° 0' 11.460" E
15° 0' 7.928" E
15° 1' 53.693" S
15° 2' 24.699" E
15° 2' 45.547" E
15° 2' 12.837" E
15° 2' 43.594" E
15° 2' 31.644" E
15° 3' 1.059" E
14° 59' 46.315" E
14° 59' 31.694" E
15° 2' 41.057" E
14° 58' 40.068" E
36°57'9" N
"""#
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