gpt4 book ai didi

ios - 当 NSPredicate 匹配带有括号的字符串时崩溃

转载 作者:行者123 更新时间:2023-12-03 20:50:57 32 4
gpt4 key购买 nike

当我尝试使用包含括号的字符串运行 NSPredicate 时,我的应用程序始终崩溃。下面是示例代码:

NSString *myString = @"test)";
NSPredicate *defaultPredicate = [NSPredicate predicateWithFormat:@"title MATCHES[cd] %@", myString];

这是生成的崩溃日志:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Can't do regex matching, reason: Can't open pattern U_REGEX_MISMATCHED_PAREN (string test, pattern test), case 1, canon 2)

在我的用例中,人们不应该使用括号搜索字符串,因此我可以通过执行类似于下面的代码的操作来清理字符串,但这并不优雅。

myString = [[myString stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""];

任何帮助或线索将不胜感激。谢谢!

最佳答案

MATCHES 用于正则表达式比较。您的表达式被视为正则表达式。如果您的表达式不是有效的正则表达式,它将失败。因此,如果您使用 MATCHES,您通常不希望未经过滤的用户输入,因为每次使用不完整的正则表达式时都会失败。

也许是另一个 String Comparison会更好。

String comparisons are, by default, case and diacritic sensitive. You can modify an operator using the key characters c and d within square braces to specify case and diacritic insensitivity respectively, for example firstName BEGINSWITH[cd] $FIRST_NAME.

BEGINSWITH
The left-hand expression begins with the right-hand expression.

CONTAINS The left-hand expression contains the right-hand expression.

ENDSWITH
The left-hand expression ends with the right-hand expression.

LIKE
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ? matches 1 character and * matches 0 or more characters.

MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

关于ios - 当 NSPredicate 匹配带有括号的字符串时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28997775/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com