gpt4 book ai didi

objective-c - Objective-c 中的正则表达式无法按预期工作

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:40 24 4
gpt4 key购买 nike

我使用 Regex 检查密码。但它没有按预期工作。我使用一些单元测试来检查正则表达式。

@implementation NSString (regexMatch)

- (BOOL)matchesRegex:(NSString *)regexPattern
{
NSError *error = nil;

NSRegularExpression* regex = [NSRegularExpression
regularExpressionWithPattern:regexPattern
options:NSRegularExpressionSearch
error:&error];

if(error)
{
NSLog(@"Error on maches regex: %@ on %@: %@", regex, self, error);
return NO;
}

NSUInteger maches = [regex numberOfMatchesInString:self
options:NSRegularExpressionSearch
range:NSMakeRange(0, [self length])];

return (maches > 0);
}

@end

正则表达式:

const static NSString *REGEX_VALID_PASS = @"(^((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[-_,.@#$%'\"]).{6,20})$)";

单元测试:

//Password 
// At least:
// - between 6 and 20 chars
// - a capital character
// - a small character
// - a digit
// - a special char: - _ , . @ # $ % ´ '
STAssertTrue([@"Pass1-" matchesRegex:REGEX_VALID_PASS], @"Password 1 failed");

STAssertTrue([@"aPrettyLongPassw0rd@" matchesRegex:REGEX_VALID_PASS], @"Password 2 failed");

STAssertTrue([@"Pw987321-_,.@#$%'`" matchesRegex:REGEX_VALID_PASS], @"Password 3 failed");

//Returns TRUE ???
STAssertFalse([@"password1@" matchesRegex:REGEX_VALID_PASS], @"Wrong password 4 works (No capital letter)");

//Returns TRUE ???
STAssertFalse([@"PASSWORD2#" matchesRegex:REGEX_VALID_PASS], @"Wrong password 5 works (No small letter)");

STAssertFalse([@"Password8" matchesRegex:REGEX_VALID_PASS], @"Wrong password 6 works (No special letter)");

STAssertFalse([@"Password$" matchesRegex:REGEX_VALID_PASS], @"Wrong password 7 works (No digit letter)");

STAssertFalse([@"PrettyLongPasswordIsWrong123#" matchesRegex:REGEX_VALID_PASS], @"Wrong password 8 works (> 20)");

STAssertFalse([@"Pw@3" matchesRegex:REGEX_VALID_PASS], @"Wrong password 9 works (< 6)");

密码“password1@”和“PASSWORD2#”返回 TRUE 但不正确。

错误:

file://localhost/Users/user/app/AppTest.m: error: testRegex (AppTest) failed: "[@"password1@" matchesRegex:REGEX_VALID_PASS]" should be false. Wrong password 4 works (No capital letter)

and


file://localhost/Users/user/app/AppTest.m: error: testRegex (AppTest) failed: "[@"PASSWORD2#" matchesRegex:REGEX_VALID_PASS]" should be false. Wrong password 5 works (No small letter)

最佳答案

您指定了 NSRegularExpressionCaseInsensitive 选项,因此表达式不区分大小写字母是有道理的。

通过指定 NSRegularExpressionCaseInsensitive 选项,(?=.*[a-z]) 将匹配任何字母,包括大写字母;同样,(?=.*[A-Z]) 也将匹配小写字母。

您失败的单元测试预期会有不同的行为:它们都检查密码是否包含大写和小写字母,而输入包含大小写相同的字母。

关于objective-c - Objective-c 中的正则表达式无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10597987/

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