替换2个特定字符之间的字符串字符
问题描述:
我试图为电子邮件清理NSString以删除域名。替换2个特定字符之间的字符串字符
所以我们说
将需要
“[email protected]****.com”
OR
testemail子@****(我还需要一种方法,可以替换“@”后的所有字符
但是对于任何域变体。
如果有人有简单的解决方案,我会非常感激。
谢谢!
答
这绝不是防弹的,但它是一个有点比以前更稳健答案。
- (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;
}
请记住,有针对包含电子邮件地址的“本地”部分没有限购“@”只要本地部分是引用,按照RFC 2822
+0
Right on,Thanks! – HenryGale 2014-08-28 18:57:59
答
string email = "[email protected]";
int atIndex = email.IndexOf('@');
string scrubbed = email.substring(0, atIndex + 1) + "****.com"
将所有字符抓到@然后附加“****。com”到最后。
答
对于4个星号代替域:
NSString *email = @"[email protected]";
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 = @"[email protected]";
NSRange at = [email rangeOfString:@"@"];
email = [email stringByReplacingCharactersInRange:NSMakeRange(at.location + at.length, email.length - at.location - at.length) withString:@"****"];
答
这应该做的伎俩,将做一个很好的分类方法。
- (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 = @"[email protected]";
NSLog(@"%@", [self stringByReplacingEmailDomainWithAsterisks:someEmail]);
返回:
[email protected]*******.com
编辑:您将需要一些错误检查,以确保你有一个很好的串/电子邮件等
添加
您必须使用正则表达式来查找模式,即在“@”之后或您选择的任何模式之后,然后您可以根据需要进行修改。 – 2014-08-28 17:58:37
你可以检出NSRange来获取特定字符的位置(在本例中为@符号),为该索引创建一个子字符串,然后在子字符串的末尾附加星号 – sfeuerstein 2014-08-28 17:59:32