使用正則表達式:RegexKitLite
下面是一個使用HTTP matching URL from the RegexKitLite documentation一個完整的例子。 RegexKitLite -componentsMatchedByRegex:
方法將返回它在字符串中找到的所有URL匹配的NSArray
。
#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);
}
編譯和運行用:
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"
)