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

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

最佳答案

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

在 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/

相关文章:

ios - React Native - NSInvalidArgumentException

ios - 如何激活选项卡 IOS

ios - 为什么将排序键用作 filterExpression 时 AWSDynamoDBScanExpression 返回空值?

ios - 使用 Swift 生成 PDF

ios - 过滤具有一对一关系的NSmanagedObject的NSArray

iphone - 使用 UITextFieldDelegate 时出现奇怪的错误

ios - 如何在我的应用程序中只打印一次警报 View ?

ios - 在 IOS 中使用 NSPredicate 按数组的一个元素过滤数组的 NSArray

swift - 我用的是 swift 。我无法将我的变量传递给另一个场景

mysql - NSPredicate SUBQUERY 用于一对多关系