当我获取存储在 .plist 文件中的正则表达式并将其提供给 NSPredicate 时,它给我一个错误。我在这里缺少什么基本的编程概念?
以前我使用的正则表达式如下所示
static let PASSWORD_REGEX: String = "^[a-zA-Z_0-9\\-#!$@~`%&*()_+=|\"\':;?/>.<,]{6,15}$"
并像这样为模式匹配提供它。并且运行良好。
func isValidPassword() -> Bool {
let passwordRegex = Constants.PASSWORD_REGEX
let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegex)
let rVal = passwordTest.evaluate(with: self)
return rVal
}
我所做的更改是,我已将此正则表达式字符串移动到一个 .plist 文件中,并从那里获取它。 :-
static let PASSWORD_REGEX: String = Constants.getCustomizableParameter(forKey: "PASSWORD_REGEX")
static func getCustomizableParameter(forKey: String) -> String {
var customizableParameters: NSDictionary?
if let customizableParametersPlistPath = Bundle.main.path(forResource: "CustomizableParameters", ofType: "plist") {
customizableParameters = NSDictionary(contentsOfFile: customizableParametersPlistPath)
}
if customizableParameters != nil {
return customizableParameters![forKey] as! String
} else {
return ""
}
}
现在,当我使用相同的密码验证功能时。它给我以下错误:-
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't do regex matching, reason: Can't open pattern U_REGEX_INVALID_RANGE (string asdasd, pattern ^[a-zA-Z_0-9\\-#!$@~`%&*()_+=|\"\':;?/>.<,]{6,15}$, case 0, canon 0)'
最佳答案
在代码中的文字字符串中,您必须转义字符(例如 \"
而不是简单的 "
)。
在 plist 中没有这样的需求。 \
字符将保留在那里,使您的模式无效。
删除额外的 \
字符,一切都会开始工作。
比较:
let PASSWORD_REGEX: String = "^[a-zA-Z_0-9\\-#!$@~`%&*()_+=|\"\':;?/>.<,]{6,15}$"
print(PASSWORD_REGEX)
输出:
^[a-zA-Z_0-9\-#!$@~`%&*()_+=|"':;?/>.<,]{6,15}$
哪个是正确的正则表达式
关于ios - 为什么在使用 .plist 文件中的 Regex 字符串时出现此错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43406697/