我正在尝试使用电子邮件清理NSString以删除域名。
所以,让我们说
“testEmail@gmail.com”
需要
“testemail子@ ****。com”
OR
testEmail @ **** (我还需要一个方法来替换“@”后的所有字符
但对于任何域名变体。
如果有人有简单的解决方案,我会非常感激。
谢谢!
答案 0 :(得分:2)
这绝不是防弹的,但它比以前的答案更有力。
- (NSString *)sanitizedStringForEmailAddress:(NSString *)address elideEntireDomain:(BOOL)elideEntireDomain
{
NSRange asperandRange = [address rangeOfString:@"@" options:NSBackwardsSearch];
NSRange domainRange = [address rangeOfString:@"." options:NSBackwardsSearch];
if (asperandRange.location != NSNotFound &&
domainRange.location != NSNotFound &&
asperandRange.location < domainRange.location)
{
NSRange elisionRange = NSMakeRange(asperandRange.location + 1, domainRange.location - asperandRange.location - 1);
if (elideEntireDomain)
{
elisionRange.length = address.length - asperandRange.location - 1;
}
NSString *elisionString = @"****";
return [address stringByReplacingCharactersInRange:elisionRange withString:elisionString];
}
return nil;
}
请记住,对于&#34; local&#34;没有任何限制。电子邮件地址的一部分,包含&#34; @&#34;只要根据RFC 2822引用本地部分。
答案 1 :(得分:1)
这应该可以做到,这将成为一个很好的类别方法。
- (NSString *)stringByReplacingEmailDomainWithAsterisks:(NSString *)emailAddress
{
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"@."];
NSArray *allComponents = [emailAddress componentsSeparatedByCharactersInSet:charSet];
NSMutableString *newString = [NSMutableString new];
[newString appendFormat:@"%@@", [allComponents firstObject]];
NSRange range = NSMakeRange(0, 1);
for (__unused int i = range.location; range.location < [allComponents[1] length]; range.location++) {
[newString appendString:@"*"];
}
[newString appendFormat:@".%@", allComponents[2]];
return [NSString stringWithFormat:@"%@", newString];
}
示例:
NSString *someEmail = @"This_isAtest@wipeOut.com";
NSLog(@"%@", [self stringByReplacingEmailDomainWithAsterisks:someEmail]);
返回:
This_isAtest@*******.com
编辑:你需要添加一些错误检查以确保你有一个好的字符串/电子邮件等。
答案 2 :(得分:0)
string email = "testEmail@gmail.com";
int atIndex = email.IndexOf('@');
string scrubbed = email.substring(0, atIndex + 1) + "****.com"
将所有角色抓到@,然后追加&#34; ****。com&#34;到最后。
答案 3 :(得分:0)
用4个星号替换域:
NSString *email = @"testEmail@gmail.com";
NSRange at = [email rangeOfString:@"@"];
NSRange com = [email rangeOfString:@".com"];
email = [email stringByReplacingCharactersInRange:NSMakeRange(at.location + at.length, com.location - at.location - at.length) withString:@"****"];
并替换@
之后的所有内容:
NSString *email = @"testEmail@gmail.com";
NSRange at = [email rangeOfString:@"@"];
email = [email stringByReplacingCharactersInRange:NSMakeRange(at.location + at.length, email.length - at.location - at.length) withString:@"****"];