views:

1679

answers:

3

Hi guys, I have been scratching my head trying to find any resources on substringing an email address I get from a textfield into getting the first part before the @ symbol. Ive tried looking at the documentation, playing around with the componentsseparatedbyString.

No luck.

Thanks for your help in advance

+6  A: 
NSString* email = @"[email protected]";
NSString* username = [[email componentsSeparatedByString:@"@"] objectAtIndex:0];

You'll want to do some error checking most likely, but that's the meat of it.

nall
Thanks, I sort of had objectAtIndex a separate entry pointing to that and it didnt work, but thanks mate, this works
Doron Katz
+3  A: 
- (NSString*)usernameFromEmail:(NSString*)email
{
    NSString* username = nil;
    NSRange range = [email rangeOfString:@"@"];
    if (range.location != NSNotFound)
    {
        username = [email substringToIndex:range.location];
    }
    return username;
}
Darren
+4  A: 

Using regular expressions:

NSString * email = @"[email protected]";
NSString * name = [email stringByMatching:@"^([^@]+)@" capture:1];
Dave DeLong
Why include a 3rd party library if you don't have to?
nall
@nall I prefer using RegexKitLite, which just requires linking in the icu library and #importing some NSString categories
Dave DeLong
@Dave I agree -- RegexKitLite is great, but it's still extra code that you have to maintain/update.
nall
@nall +1 good point. I keep things like RKL checked out from SVN to a directory, then just reference the files in my projects. Every now and then I run a script the updates all my checked out projects, and then all my projects that use RKL (or whatever) get automatically updated. Ditto on my private frameworks. I build them directly to ~/Library/Frameworks so that everything I build automatically gets the latest versions.
Dave DeLong