Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate 1 NSString into two NSStrings by whiteSpace

I have an NSString which initially looked like <a href="http://link.com"> LinkName</a>. I removed the html tags and now have an NSString that looks like

http://Link.com   SiteName

how can I separate the two into different NSStrings so I would have

http://Link.com

and

SiteName

I specifically want to show the SiteName in a label and just use the http://Link.com to open in a UIWebView but I can't when it is all one string. Any suggestions or help is greatly appreciated.

like image 592
FreeAppl3 Avatar asked Oct 12 '11 21:10

FreeAppl3


1 Answers

NSString *s = @"http://Link.com   SiteName";
NSArray *a = [s componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(@"http: '%@'", [a objectAtIndex:0]);
NSLog(@"site: '%@'", [a lastObject]);

NSLog output:

http: 'http://Link.com'
site: 'SiteName'

Bonus, handle a site name with an embedded space with a RE:

NSString *s = @"<a href=\"http://link.com\"> Link Name</a>";
NSString *pattern = @"(http://[^\"]+)\">\\s+([^<]+)<";

NSRegularExpression *regex = [NSRegularExpression
                              regularExpressionWithPattern:pattern
                              options:NSRegularExpressionCaseInsensitive
                              error:nil];

NSTextCheckingResult *textCheckingResult = [regex firstMatchInString:s options:0 range:NSMakeRange(0, s.length)];
NSString *http = [s substringWithRange:[textCheckingResult rangeAtIndex:1]];
NSString *site = [s substringWithRange:[textCheckingResult rangeAtIndex:2]];

NSLog(@"http: '%@'", http);
NSLog(@"site: '%@'", site);

NSLog output:

http: 'http://link.com'
site: 'Link Name'
like image 99
zaph Avatar answered Nov 26 '22 16:11

zaph