如何在Objective-C中屏蔽电子邮件地址字符串?
我想按以下步骤屏蔽电子邮件
mugunth@gmail.com转换为m ***** h@gmail.com
答案 0 :(得分:1)
找到@
的范围,并通过从范围位置减小2来创建新范围。创建一个包含*
个字符的新字符串,并以新的范围长度重复。现在,替换范围内的字符。
NSArray *emails = @[@"mugunth@gmail.com",@"mugunthgmail.com",@"m@gmail.com"];
NSString *emailRegex = @"[A-Z0-9a-z._%+-]{2,}+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
for (NSString *email in emails) {
if ([emailTest evaluateWithObject:email]) {
NSRange range = [email rangeOfString:@"@"];
NSRange newRange = NSMakeRange(1, range.location-2);
NSString *replace = [@"" stringByPaddingToLength:newRange.length withString:@"*" startingAtIndex:0];
NSString * maskedEmail = [email stringByReplacingCharactersInRange:newRange withString:replace];
NSLog(@"%@",maskedEmail);//m*****h@gmail.com
} else {
NSLog(@"Invalid Email Address");
}
}
m ***** h@gmail.com
无效的电子邮件地址
无效的电子邮件地址