我怎样才能获得字符串的特定部分?

时间:2012-08-14 07:04:02

标签: iphone nsstring split

我有一个字符串:

"This is test string http://www.google.com and it is working."

我想从上面的字符串中只获得链接(http://www.google.com)。我怎么能得到它?

3 个答案:

答案 0 :(得分:1)

它应该像这样工作:

NSString *test = @"This is test string http://www.google.com and it is working.";

NSString *string = [test stringByAppendingString:@" "];

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"https?://[^ ]* "
                                                                       options:0
                                                                         error:&error];
NSArray *matches = [regex matchesInString:string
                                  options:0
                                    range:NSMakeRange(0, [string length])];

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *url = [string substringWithRange:matchRange];

    NSLog(@"Found URL: %@", url);
}

您可以在此处找到有关使用NSRegularExpression的更多信息:

https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

答案 1 :(得分:0)

查看NSString类文档 - 有很多方法可以找到某些子字符串格式的位置,在分隔符上拆分字符串,以及提取子字符串等。

e.g。在上面的示例中,如果要在字符串中提取任何嵌入的URL,可以先使用以下方法拆分字符串:

NSArray *substrings = [myString componentsSeparatedByString:@" "];

然后在结果数组中,遍历它并找出它是否有'http'字符串:

for (int i=0;i<[substrings length];i++) {
   NSString aStr = [substrings objectAtIndex:i];
   if ([aStr rangeOfString:@"http"].location != NSNotFound) {
        NSLog(@"I found a http url:%@", aStr);
   }
}

答案 2 :(得分:0)

这将像CHARM一样工作:

NSString *totalString = @"This is test string http://www.google.com and it is working.";
NSLog(@"%@", totalString);

NSRange urlStart = [totalString rangeOfString: @"http"];
NSRange urlEnd = [totalString rangeOfString: @".com"];
NSRange resultedMatch = NSMakeRange(urlStart.location, urlEnd.location - urlStart.location + urlEnd.length);

NSString *linkString = [totalString substringWithRange:resultedMatch];

NSLog (@"%@", linkString);