I need to use NSRegularExpression in my Swift application to check if latitude and longitude coordinates informed by user is in correct format.
My regular expression: -?[0-9]{1,3}[.]{1}[0-9]{6}
This regular expression work but not fully. It make to:
- The coordinate can begin by
-
- The coordinate can then begin by 3 maximum numbers
- Then the characters
.
is necessary - And to finish 6 numbers are necessary but not more
The problems are:
- If I begin by every characters, the expression return true:
?.-33.476543
- If then I paste more of 3 numbers the expression return true:
-33555.476543
- And if I paste more of 6 numbers after the
.
the expression return true:-33.476543546565565765
It's normal but how can I create a "patern" to force user to informed only 6 numbers or only begin by -
character for exemple?
The regular expression in code:
let regex = NSRegularExpression("-?[0-9]{1,3}[.]{1}[0-9]{6}")
if regex.matches(self.latitude) && regex.matches(self.longitude) {
self.coordinatesValid = true
} else {
self.coordinatesValid = false
}
My NSRegularExpression extension:
import Foundation
extension NSRegularExpression {
convenience init(_ pattern: String) {
do {
try self.init(pattern: pattern)
} catch {
preconditionFailure("Illegal regular expression: \(pattern).")
}
}
func matches(_ string: String) -> Bool {
let range = NSRange(location: 0, length: string.utf16.count)
return firstMatch(in: string, options: [], range: range) != nil
}
}