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

Why am i getting this error while using Regex string from a .plist file?

当我获取存储在 .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 中的值如下:-

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

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}$

哪个是正确的正则表达式