Reputation: 14835
I have a VERY long NSString
. It contains about 100 strings I need to pull out of it, all randomly scattered throughout. They are all commonly are between imgurl=
and &
.
I could use NSRange
and just loop through pulling out each string, but I'm wondering if there is a quicker was to pick out everything in a simple API call? Maybe something I am missing here?
Looking for the quickest way to do this. Thanks!
Upvotes: 1
Views: 88
Reputation: 5409
If you feel adventurous then you can use regular expression. Since you said that the string you are looking is between imgurl
and &
, I assumed its a url and made the sample code to do the same.
NSString *str = @"http://www.example.com/image?imgurl=my_image_url1&imgurl=myimageurl2&somerandom=blah&imgurl=myurl3&someother=lol";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?:imageurl=)(.*?)(?:&|\\r)"
options:NSRegularExpressionCaseInsensitive
error:&error];
//should do error checking here...
NSArray *matches = [regex matchesInString:str
options:0
range:NSMakeRange(0, [str length])];
for (NSTextCheckingResult *match in matches)
{
//[match rangeAtIndex:0] <- gives u the whole string matched.
//[match rangeAtIndex:1] <- gives u the first group you really care about.
NSLog(@"%@", [str substringWithRange:[match rangeAtIndex:1]]);
}
If I were you, I will still go with @bobnoble method because its easier and simpler compared to regex. You will have to do more error checking using this method.
Upvotes: 2
Reputation: 5824
Using NSString
methods componentsSeparatedByString
and componentsSeparatedByCharactersInSet
:
NSString *longString = some really long string;
NSArray *longStringComponents = [longString componentsSeparatedByString:@"imgurl="];
for (NSString *string in longStringComponents){
NSString *imgURLString = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"&"]] firstObject];
// do something with imgURLString...
}
Upvotes: 2