Home > OS >  Regex for floating points, range and zero
Regex for floating points, range and zero

Time:04-20

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

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