syed imty
syed imty

Reputation: 1028

How to extract email address from string using NSRegularExpression

I am making an iphone application. I have a scenario where i have a huge string, which has lot of data, and i would like to extract only email addresses from the string.

For example if the string is like

asdjasjkdh asdhajksdh jkashd [email protected] asdha jksdh asjdhjak sdkajs [email protected]

i should extract "[email protected]" and "[email protected]"

and i also want to extract only date, from the string

For example if the string is like

asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd [email protected] asdha jksdh asjdhjak sdkajs [email protected]

i should extract "01/01/2012" and "12/11/2012"

A small code snipet, will be very helpful.

Thanks in advance

Upvotes: 1

Views: 1944

Answers (3)

Anton
Anton

Reputation: 4018

This will do what you want:

// regex string for emails (feel free to use a different one if you prefer)
NSString *regexString = @"([A-Za-z0-9_\\-\\.\\+])+\\@([A-Za-z0-9_\\-\\.])+\\.([A-Za-z]+)";

// experimental search string containing emails
NSString *searchString = @"asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd [email protected] asdha jksdh asjdhjak sdkajs [email protected]";

// track regex error
NSError *error = NULL;

// create regular expression
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:0 error:&error];

// make sure there is no error
if (!error) {

    // get all matches for regex
    NSArray *matches = [regex matchesInString:searchString options:0 range:NSMakeRange(0, searchString.length)];

    // loop through regex matches
    for (NSTextCheckingResult *match in matches) {

        // get the current text
        NSString *matchText = [searchString substringWithRange:match.range];

        NSLog(@"Extracted: %@", matchText);

    }

}

Using your sample string above:

asdjasjkdh 01/01/2012 asdhajksdh jkas 12/11/2012 hd [email protected] asdha jksdh asjdhjak sdkajs [email protected]

The output is:

Extracted: [email protected]
Extracted: [email protected]

To use the code, just set searchString to the string you want to search. Instead of the NSLog() methods, you'll probably want to do something with the extracted strings matchText. Feel free to use a different regex string to extract emails, just replace the value of regexString in the code.

Upvotes: 10

Sten
Sten

Reputation: 3864

NSArray *chunks = [mylongstring componentsSeparatedByString: @" "];

for(int i=0;i<[chunks count];i++){
    NSRange aRange = [chunks[i] rangeOfString:@"@"];
    if (aRange.location !=NSNotFound) NSLog(@"email %@",chunks[i] );
}

Upvotes: 1

Anirudha
Anirudha

Reputation: 32797

You can use this regex to match emails

 [^\s]*@[^\s]*

and this regex to match dates

 \d+/\d+/\d+

Upvotes: 0

Related Questions