iOSDev
iOSDev

Reputation: 1028

Objective-C get email addresses from string

I have a NSString containing several email addresses and some other random text. I would like to be able to pull out just the email addresses. They all have the same domain, say @business.com, for example. What would be the best approach to this?

Sample string (HTML)

            <td colspan="2" bgcolor="#000000">
        <p align="center"><b><font color="#FFFFFF" size="2">title</font></b></p></td>
    </tr>

    <tr>
        <td valign="top">

<font size="2"><b>lastname</b>, firstname A.,&nbsp;[email protected]</font><br>

<font size="2"><b>lastname</b>, firstname A.,&nbsp;[email protected]</font><br>

<font size="2"><b>lastname</b>, firstname,&nbsp;[email protected]</font><br>

<font size="2"><b>lastname</b>, firstname,&nbsp;[email protected]</font><br>

Upvotes: 1

Views: 977

Answers (2)

Jeremy
Jeremy

Reputation: 9030

I took the liberty of creating an example for you since I was interested myself:

NSString *someHTML = @"<b>lastname</b>, firstname,&nbsp;[email protected]</font><b>lastname</b>, firstname,&nbsp;[email protected]</font><b>lastname</b>, firstname,&nbsp;[email protected]</font>";
NSRegularExpression *regex   = [NSRegularExpression regularExpressionWithPattern:@"(\\w*@business.com)" options: NSRegularExpressionUseUnixLineSeparators error:nil];
NSArray *matches = [regex matchesInString:someHTML options:NSMatchingWithTransparentBounds range:NSMakeRange(0, someHTML.length)];
for (NSTextCheckingResult *result in matches)
{
    NSString *email = [someHTML substringWithRange:[result range]];
    NSLog(email);
}

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96937

Take a look at using NSRegularExpression with a pattern that finds email addresses.

Upvotes: 1

Related Questions