I need regex that matches zero, integer and floating point numer in live input but also with length after decimal separator. So it should be ok when user tap
- 0, 0,2, 1,1234
- also it should be valid if typing 0 then 0, then 0,1 etc...
- also if user tap "." and decimalSeparator is "," validation should fail. The problem is that my regex does not match zero:
let decimalSeparator = NumberFormatter().decimalSeparator ?? ","
let range = 4
var pattern: String {
return "^(?![0.] $)[0-9]{0,10}(?:\\\(decimalSeparator)[0-9]{0,\(range)})?$"
}
let exp = try NSRegularExpression(pattern: pattern, options: .caseInsensitive).firstMatch(in: string,
options: [],
range: NSRange(location: 0,
length: string.count))```
CodePudding user response:
The (?![0.] $)
negative lookahead matches a location that is not immediately followed with one or more .
or zeros till the end of string.
Thus, to allow matching zeros, you need to get rid of the lookahead:
let decimalSeparator = NumberFormatter().decimalSeparator ?? ","
let range = 4
var pattern: String {
return "^[0-9]{0,10}(?:\\\(decimalSeparator)[0-9]{0,\(range)})?$"
}
let exp = try NSRegularExpression(pattern: pattern, options: .caseInsensitive).firstMatch(in: string,
options: [],
range: NSRange(location: 0,
length: string.utf16.count))