import Foundation
let pattern = #"^(?(DEFINE)(?'longitude'[-+]?(?|180(?>\.0+)?|(?>1[0-7]\d|[1-9]?\d)(?>\.\d+)?))(?'latitude'[-+]?(?|90(?>\.0+)?|[1-8]?\d(?>\.\d+)?)))LINESTRING\s*\((?>(?:(?(?<=\()(?>\s*)|(?>\s*,\s*))(?P>longitude)(?>\s*)(?P>latitude)\s*){2,})\)$"#
let regex = try! NSRegularExpression(pattern: pattern)
let testString = #"LINESTRING(-5.764642842113973 41.915708669165184 ,-5.7630935311317435 41.91684083791108,-5.765079036355018 41.918309783201565,-5.765336528420449 41.918293068151534,-5.765593685209751 41.91818504391658,-5.7656215131282815 41.91791859998719,-5.764469504356383 41.916424697127816,-5.764911398291588 41.91594194048126 , -5.764642842113973 41.915708669165184 )"#
let stringRange = NSRange(location: 0, length: testString.utf16.count)
let substitutionString = #""#
let lookupRange = (testString as NSString).range(of: pattern, options: .regularExpression, range: stringRange)
if lookupRange.intersection(stringRange) != nil {
let result = regex.stringByReplacingMatches(in: testString, range: lookupRange, withTemplate: substitutionString)
print(result)
} else {
print("No matches were found.")
}
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