Cocoa 创建 NSRegularExpression 时出现错误 2048

Cocoa Error 2048 on NSRegularExpression Creation

我正在尝试从以下内容创建正则表达式:

#define RegEX_1_UPPER_1_SPECIAL @"((?=.*[A-Z])(?=.*[$@!%*?&-+_()]).{8,})"

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: RegEX_1_UPPER_1_SPECIAL options:0 error:&error];

但是,不幸的是 returns 我出现了以下错误:

Error Domain=NSCocoaErrorDomain Code=2048 "The operation couldn’t be completed. (Cocoa error 2048.)" UserInfo=0x7ff6f51b5af0 {NSInvalidValue=(?=.*[A-Z])(?=.*[$@!%*?&-+_]).{8,15}}

问题出在您的特殊字符集合中的连字符。连字符在 [] 中有特殊含义,即字符范围(例如 [A-Z])。如果你想搜索文字连字符,你必须转义:

#define RegEX_1_UPPER_1_SPECIAL @"((?=.*[A-Z])(?=.*[$@!%*?&\-+_()]).{8,})"