需求描述:
- 如果是多位整数, 限制首位不能为0, 整数位最多9位;
- 首位不能为小数点;
- 如果是小数, 小数位最多两位;
代码片段:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if textField.text?.count == 1 && string.isEmpty {
return true
}
// [1-9]限制多位整数, 首位的范围; {0, 8}表示减去第一位, 剩余整数位的个数(如9位整数, 减去第一位剩下8位, 用{0, 8}); 小数位{0,2}表示小数位的个数; Note: 使用过程自行修改{0, 8}, {0, 2}范围
let expression = "^[1-9]\\d{0,8}?$*((\\.|,)[0-9]{0,2})?$|^0{1}((\\.|,)[0-9]{0,2})?$"
let regex = try? NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex?.numberOfMatches(in: newString, options: .reportProgress, range: NSRange(location: 0, length: (newString as NSString).length))
return numberOfMatches != 0
}