开发者

Find an Url in a NSString or find a String between two Strings

开发者 https://www.devze.com 2022-12-16 05:17 出处:网络
I have a NSString with this content: <?xml version=\"1.0\" encoding=\"UTF-8\"?> <rsp stat=\"ok\">

I have a NSString with this content:

<?xml version="1.0" encoding="UTF-8"?>
<rsp stat="ok">
 <mediaid>y2q62</mediaid>
 <mediaurl>http://twitpic.com/url</mediaurl>
</rsp>
开发者_JS百科

Now I want to get the twitpic-Url in a new NSString without all the other Strings. How can I make this? Can I search in NSStrings? Like: Find the strings between the Strings ? Or can I find directly URLs in a NSString?

Thanks for your help!


Use a regex: RegexKitLite

Here's a complete example using the HTTP matching URL from the RegexKitLite documentation. The RegexKitLite -componentsMatchedByRegex: method will return a NSArray of all the URL matches it finds in the string.

#import <Foundation/Foundation.h>
#import "RegexKitLite.h"

int main(int argc, char *argv[]) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

  NSString *stringToSearch =
    @"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
    @"<rsp stat=\"ok\">\n"
    @" <mediaid>y2q62</mediaid>\n"
    @" <mediaurl>http://twitpic.com/url</mediaurl>\n"
    @"</rsp>\n";

  NSString *urlRegex = @"\\bhttps?://[a-zA-Z0-9\\-.]+(?:(?:/[a-zA-Z0-9\\-._?,'+\\&%$=~*!():@\\\\]*)+)?";

  NSArray *matchedURLsArray = [stringToSearch componentsMatchedByRegex:urlRegex];

  NSLog(@"matchedURLsArray: %@", matchedURLsArray);

  [pool release];
  pool = NULL;

  return(0);
}

Compile and run with:

shell% gcc -arch i386 -o url url.m RegexKitLite.m -framework Foundation -licucore
shell% ./url
2010-01-14 16:05:32.874 url[71582:903] matchedURLsArray: (
    "http://twitpic.com/url"
)


Use NSXMLParser after converting the string to NSData.

0

精彩评论

暂无评论...
验证码 换一张
取 消