'Regex for floating points, range and zero

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

  1. 0, 0,2, 1,1234
  2. also it should be valid if typing 0 then 0, then 0,1 etc...
  3. 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))```


Solution 1:[1]

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))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1