NSString中解析URL

总结几种方法达到这种目的。

1.正则表达式法。

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://abc.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://abc.com/efg.php?EFAei687e3EsA'

至于这个正则表达式,是从网上找的,请看这儿

2.系统的NSDataDetector

NSString *string = @"This is a sample of a http://abc.com/efg.php?EFAei687e3EsA sentence with a URL within it."; NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil]; NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])]; for (NSTextCheckingResult *match in matches) { if ([match resultType] == NSTextCheckingTypeLink) { NSURL *url = [match URL]; NSLog(@"found URL: %@", url); } }

3.直接操作NSString

NSURL *url; NSMutableArray *listItems = [[someString componentsSeparatedByString:@" "] mutableCopy]; for(int i=0;i<[listItems count];i++) { NSString *str=[listItems objectAtIndex:i]; if ([str rangeOfString:@"http://"].location == NSNotFound) NSLog(@"Not url"); else url=[NSURL URLWithString:str]; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值