gpt4 book ai didi

ios - 无法在 objective-c 中创建正则表达式

转载 作者:行者123 更新时间:2023-12-01 20:05:28 24 4
gpt4 key购买 nike

我有一个正则表达式来检查我正在使用以下正则表达式模式的Max 70 alphanumeric characters and special characters: ' / \\ - ; @ and space-

^[a-zA-Z0-9,.-\s'\\\/@]{0,70}$

请注意:在 https://regex101.com中对此进行测试非常正常

和以下代码将其与字符串匹配-
NSString *String = area@123\\
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-zA-Z0-9,.-\s'\\\/@]{0,70}$" options:NSRegularExpressionCaseInsensitive error:&error];

NSAssert(regex, @"Unable to create regular expression");
NSRange textRange = NSMakeRange(0, string.length);
NSRange matchRange = [regex rangeOfFirstMatchInString:string options:NSMatchingReportProgress range:textRange];

最初它显示了转义序列错误,为此我将模式更改为- ^[a-zA-Z0-9,.-\\s'\\\\//@]{0,70}$
现在,它导致消息崩溃-
Assertion failure in +[UMValidations validateString:withPattern:]
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unable to create regular expression

现在,当此模式在regex测试器上正常工作时,发生了什么错误。

最佳答案

当您在Objective-C中编写正则表达式模式时,带有特殊字符的反斜杠必须加倍。此外,您还需要转义连字符(或将其放在字符类的开头/结尾)。

@"^[a-zA-Z0-9,.\\-\\s'\\\\/@]{0,70}$"
^^ ^^ ^^^^

您不需要转义 /。您需要使用4个反斜杠来定义文字 \,因为正则表达式引擎使用文字反斜杠(在Objective-C字符串文字中定义为 "\\")中转义特殊字符并表示文字 \,即Objective-C中的文字反斜杠字符串文字必须加倍(文字字符串模式中的 \\(因此,定义为 "\\\\")将与输入中的文字 \相匹配)。要点是字符串文字中的 \可以形成转义序列,例如 "\n"(换行符)或 "\r"(回车符)等。因此,转义分为两层:一层用于Objective-C引擎,另一层用于转义。 -用于正则表达式(在这种情况下为ICU)库。

参见 Objective-C demo:
NSString *String = @"area@123\\";
NSRegularExpression *regex = @"(?i)^[a-z0-9,.\\-\\s'\\\\/@]{0,70}$";
NSPredicate * Test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
if ([Test evaluateWithObject:String]) {
NSLog (@"yes");
} else {
NSLog (@"no");
}

关于ios - 无法在 objective-c 中创建正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037969/

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