2012-05-08 128 views
3

我有一個非常長的字符串,我只想提取該字符串內的某些字符串。我怎樣才能做到這一點?如何去掉字符串?

,比如我有:

this is the image <img src="http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg"> and it is very beautiful. 

是的,現在我想獲得這串長長的一串並獲得唯一http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg

請告訴我,我怎麼能做到這一點。

回答

0

您可以使用正則表達式是:

NSRegularExpression* regex = [[NSRegularExpression alloc] initWithPattern:@"src=\"([^\"]*)\"" options:NSRegularExpressionCaseInsensitive error:nil]; 
NSString *text = @"this is the image <img src=\"http://vnexpress.net/Files/Subject/3b/bd/67/6f/chungkhoan-xanhdiem2.jpg\"> and it is very beautiful."; 
NSArray *imgs = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])]; 
if (imgs.count != 0) { 
    NSTextCheckingResult* r = [imgs objectAtIndex:0]; 
    NSLog(@"%@", [text substringWithRange:[r rangeAtIndex:1]]); 
} 

這個正則表達式的心臟解決方案:

src="([^"]*)" 

它匹配src屬性的內容,並捕獲引號之間的內容(注意一對括號)。然後在[r rangeAtIndex:1]中檢索此標題,並用於提取您正在查找的字符串部分。

+0

非常感謝,這正是我想要的。 – user1035877

0

您應該使用正則表達式,可能使用NSRegularExpression類。

這裏有一個例子,你想要做什麼(從here):

- (NSString *)stripOutHttp:(NSString *)httpLine 
{ 
    // Setup an NSError object to catch any failures 
    NSError *error = NULL; 
    // create the NSRegularExpression object and initialize it with a pattern 
    // the pattern will match any http or https url, with option case insensitive 
    NSRegularExpression *regex = [NSRegularExpression 
     regularExpressionWithPattern:@"https?://([-\\w\\.]+)+(:\\d+)?(/([\\w/_\\.]*(\\?\\S+)?)?)?" 
          options:NSRegularExpressionCaseInsensitive 
           error:&error]; 
    // create an NSRange object using our regex object for the first match in the string httpline 
    NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:httpLine 
                 options:0 
                  range:NSMakeRange(0, [httpLine length])]; 
    // check that our NSRange object is not equal to range of NSNotFound 
    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) 
    { 
     // Since we know that we found a match, get the substring from the parent 
     // string by using our NSRange object 
     NSString *substringForFirstMatch = [httpLine substringWithRange:rangeOfFirstMatch]; 
     NSLog(@"Extracted URL: %@",substringForFirstMatch); 
     // return the matching string 
     return substringForFirstMatch; 
    } 

    return NULL; 
} 
0
NSString *urlString = nil; 
NSString *htmlString = //Your string; 

NSScanner *scanner = [NSScanner scannerWithString:htmlString]; 

[scanner scanUpToString:@"<img" intoString:nil]; 
if (![scanner isAtEnd]) { 
    [scanner scanUpToString:@"http" intoString:nil]; 
    NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:@">"]; 
    [scanner scanUpToCharactersFromSet:charset intoString:&urlString]; 
} 
NSLog(@"%@", urlString);