为什么我在使用.plist文件中的Regex字符串时出现此错误?

时间:2017-04-14 06:56:21

标签: ios swift nspredicate

当我获取存储在.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 ""
    }
}

我的plist中的值如下: - enter image description here

现在我正在使用相同的密码验证功能。它给了我以下错误: -

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

1 个答案:

答案 0 :(得分:2)

在代码中的文字字符串中,您必须转义字符(例如\"而不是简单的")。

在plist中没有这样的需要。 \字符将保留在那里,使您的图案无效。

删除其他\个字符,一切都会开始工作。

比较

let PASSWORD_REGEX: String = "^[a-zA-Z_0-9\\-#!$@~`%&*()_+=|\"\':;?/>.<,]{6,15}$"
print(PASSWORD_REGEX)

输出:

^[a-zA-Z_0-9\-#!$@~`%&*()_+=|"':;?/>.<,]{6,15}$

哪个是正确的正则表达式