2017-04-14 17 views
0

当我获得存储在.plist文件中的正则表达式并将其提供给NSPredicate时,它给我一个错误。我在这里错过了什么基本的编程概念?为什么我在使用.plist文件中的正则表达式字符串时出现此错误?

以前我是使用一个正则表达式像下面

static let PASSWORD_REGEX: String = "^[a-zA-Z_0-9\\-#[email protected]~`%&*()_+=|\"\':;?/>.<,]{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\\-#[email protected]~`%&*()_+=|\"\':;?/>.<,]{6,15}$, case 0, canon 0)' 

回答

2

在代码中,你必须转义字符(例如的替代\"简单")一个字符串。

在plist中没有这种需要。 \角色将留在那里,使您的模式无效。

删除额外的\字符,一切都将开始工作。

比较:

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

输出:

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

这是正确的正则表达式

相关问题