How to Extract a Url from a Sentence That Is in a Nsstring

How can I extract a URL from a sentence that is in a NSString?

Edit: I'm going to go out on a limb here and say you should probably use NSDataDetector as Dave mentions. Far less prone to error than regular expressions.


Take a look at regular expressions. You can construct a simple one to extract the URL using the NSRegularExpression class, or find one online that you can use. For a tutorial on using the class, see here.


The code you want essentially looks like this (using John Gruber's super URL regex):

NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))" options:NSRegularExpressionCaseInsensitive error:NULL];
NSString *someString = @"This is a sample of a http://example.com/efg.php?EFAei687e3EsA sentence with a URL within it.";
NSString *match = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]];
NSLog(@"%@", match); // Correctly prints 'http://example.com/efg.php?EFAei687e3EsA'

That will extract the first URL in any string (of course, this does no error checking, so if the string really doesn't contain any URL's it won't work, but take a look at the NSRegularExpression class to see how to get around it.

Using NSRegularExpression to extract URLs on the iPhone

The method matchesInString:options:range: returns an array of NSTextCheckingResult objects. You can use fast enumeration to iterate through the array, pull out the substring of each match from your original string, and add the substring to a new array.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"http?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" options:NSRegularExpressionCaseInsensitive error:&error];

NSArray *arrayOfAllMatches = [regex matchesInString:httpLine options:0 range:NSMakeRange(0, [httpLine length])];

NSMutableArray *arrayOfURLs = [[NSMutableArray alloc] init];

for (NSTextCheckingResult *match in arrayOfAllMatches) {
NSString* substringForMatch = [httpLine substringWithRange:match.range];
NSLog(@"Extracted URL: %@",substringForMatch);

[arrayOfURLs addObject:substringForMatch];
}

// return non-mutable version of the array
return [NSArray arrayWithArray:arrayOfURLs];

Extracting URLs from NSString into NSMutableString

None of the code you posted so far can result in the exception you posted.

But the following code is incorrect:

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
NSString* substringForCurrMatch = [s.URL path];
[allRepoString appendString:substringForCurrMatch];
[allRepoString appendString:@";"];
}

You do not want to call the path method on s.URL. To get the full URL as a string, use absoluteString. This will give you the URL as a string. path just gives you the path portion of the URL.

NSMutableString * allRepoString = [NSMutableString string];  
for (NSTextCheckingResult *s in matches) {
NSString* substringForCurrMatch = [s.URL absoluteString];
[allRepoString appendString:substringForCurrMatch];
[allRepoString appendString:@";"];
}

Objective-C - Finding a URL within a string

No need to use RegexKitLite for this, since iOS 4 Apple provide NSDataDetector (a subclass of NSRegularExpression).

You can use it simply like this (source is your string) :

NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray* matches = [detector matchesInString:source options:0 range:NSMakeRange(0, [source length])];

Trying to extract an image URL from an NSString

This may help you:

- (void)viewDidLoad {
[super viewDidLoad];

NSString *description = @"<p>The post <a rel=\"nofollow\" href=\"http://www.raywenderlich.com/123606/video-tutorial-adaptive-layout-part-8-conclusion\">Video Tutorial: Adaptive Layout Part 8: Conclusion</a> appeared first on <a rel=\"nofollow\" href=\"http://www.raywenderlich.com\">Ray Wenderlich</a>.</p>";

NSString *url = [self extractFromString:description start:@"href=\"" end:@"\">"];
NSLog(@"%@",url);

}

-(NSString*)extractFromString:(NSString*)string start:(NSString*)start end:(NSString*)end{

NSRange r1=[string rangeOfString:start];
NSRange r2 = [string rangeOfString:end];
NSRange rSub = NSMakeRange(r1.location + r1.length, r2.location - r1.location - r1.length);

NSString *extractedString=[string substringWithRange:rSub];
return extractedString;
}

Getting a value from url by using components separated by string

You need to convert your string to url first and use the pathComponents method to access each components of that url.

Objective C:

NSURL *url                 = [NSURL URLWithString:@"ttps://google.com/image/ghwUT23Y.jpeg"];
NSMutableArray *components = [[url pathComponents] mutableCopy];
NSString *fileName = [components lastObject];
[components removeLastObject];
NSString *section = [components lastObject];
NSLog(@"File : %@, Section: %@",fileName, section);

Swift

let url        = URL(string: "https://google.com/image/ghwUT23Y.jpeg")
var components = url?.pathComponents
let fileName = components?.popLast()
let section = components?.popLast()

How to extract and remove scheme name from NSURL?

You can look at it like this (mostly untested code, but you get the idea):

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSLog(@"url: %@", url);
NSLog(@"scheme: %@", [url scheme]);
NSLog(@"query: %@", [url query]);
NSLog(@"host: %@", [url host]);
NSLog(@"path: %@", [url path]);

NSDictionary * dict = [self parseQueryString:[url query]];
NSLog(@"query dict: %@", dict);
}

So you can do this:

NSString * strNoURLScheme = 
[strMyURLWithScheme stringByReplacingOccurrencesOfString:[url scheme] withString:@""];

NSLog(@"URL without scheme: %@", strNoURLScheme);

parseQueryString

- (NSDictionary *)parseQueryString:(NSString *)query
{
NSMutableDictionary *dict = [[[NSMutableDictionary alloc] initWithCapacity:6] autorelease];
NSArray *pairs = [query componentsSeparatedByString:@"&"];

for (NSString *pair in pairs) {
NSArray *elements = [pair componentsSeparatedByString:@"="];
NSString *key = [[elements objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *val = [[elements objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[dict setObject:val forKey:key];
}
return dict;
}

Extract URL from HTML and keep the text if there is any

You can do this like:

NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink
error:&error];

[detector enumerateMatchesInString:someString
options:0
range:NSMakeRange(0, someString.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{
if (result.resultType == NSTextCheckingTypeLink)
{
NSString *str = [NSString stringWithFormat:@"%@",result.URL];
NSLOG(%@,str);

}
}];

Hope it helps.....:)

Extract part of URL

First of all, create a NSURL. Then, use the querymethod to get the query string part:

NSURL    * url = [ NSURL URLWithString: @"... your url ..." ];
NSString * q = [ url query ];

Then you can use the NSString methods to isolate the needed part.

IOS Convert URL string to NSString?

It is Unicode han characters in your urlString thats why it is not converting.

Replace %u to \u and you will get your String.

NSString *str=@"%3CTEXTFORMAT%20LEADING%3D%222%22%3E%3CP%20ALIGN%3D%22LEFT%22%3E%3CFONT%20FACE %3D%22Arial%22%20SIZE%3D%2212%22%20COLOR%3D%22%23000000%22%20LETTERSPACING%3D%220%22%20KERNING%3D%220%22%3E%u53F0%u5317%u7E2323141%u65B0%u5E97%u6C11%u6B0A%u8DEF130%u5DF714%u865F5%u6A13%3C/FONT%3E%3C/P%3E%3C/TEXTFORMAT%3E";
str=[str stringByReplacingOccurrencesOfString:@"%u" withString:@"\\u"];
NSString *convertedStr=[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"converted string is %@ \n",convertedStr);

output :---------------

converted string is <TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Arial" SIZE="12" COLOR="#000000" LETTERSPACING="0" KERNING="0">\u53F0\u5317\u7E2323141\u65B0\u5E97\u6C11\u6B0A\u8DEF130\u5DF714\u865F5\u6A13</FONT></P></TEXTFORMAT>

for more Info follow this url

This is chinese unicode char
here is some code that will prove it:

NSString *newStr=@"\u53F0\u5317\u7E2323141\u65B0\u5E97\u6C11\u6B0A\u8DEF130\u5DF714\u865F5\u6A13";
NSLog(@"chinese string is %@",[newStr stringByReplacingPercentEscapesUsingEncoding:NSUTF16StringEncoding]);

output:----------------------
台北縣23141新店民權路130巷14號5樓

go to google translate converting this string will give you someone's address.
as :-

Citizens Xindian, Taipei County 23141 Road 130, 5th Floor, No. 14, Lane



Related Topics



Leave a reply



Submit