Jack Humphries
Jack Humphries

Reputation: 13267

Create NSString from certain point on of other NSString

I have a NSString with the following text:

You can now download "file.png" from "http://www.example.com/RANDOM.png"

How can I create a new NSString with the URL from that string? I would want:

http://www.example.com/RANDOM.png

I would normally just remove the beginning text, but "file.png" could be any file name of any length and cannot be removed with stringByReplacingOccurrencesOfString (since I don't know what it is). Any ideas of how to remove everything up to the end of from "? Thanks for your help.

Upvotes: 0

Views: 143

Answers (2)

graver
graver

Reputation: 15213

The best way is to use regular expression that will recognize the url. Here is an example which uses the URL match RegEx from @gruber, you might have to tweak it a bit depending on the actual output of the server:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))" options:NSRegularExpressionAnchorsMatchLines | NSRegularExpressionAllowCommentsAndWhitespace error:NULL];
NSRange range = [regex rangeOfFirstMatchInString:myString options:0 range:NSMakeRange(0, [myString length])];
NSString *URL = [myString substringWithRange:range];

Upvotes: 1

JustSid
JustSid

Reputation: 25318

NSRange range = [string rangeOfString:@"from \""];
NSString *URL = [string substringFromIndex:range.location + range.length];

Error checking might be a good idea (ie range.location != NSNotFound). You'd also have to strip the last " from the string, but there is a substringToIndex: method which, combined with the strings length, can do this (I leave this up to you, its trivial).

Upvotes: 3

Related Questions