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 NSString
s 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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With