2011-05-05 34 views
3

嘗試使用「捕獲括號」剛組的位,我感興趣的是得到URL一些HTML我解析(在iPhone上)的。捕獲括號使用正則表達式對iphone

我現在有這:

NSString *imageHtml; //a string with some HTML in it 

NSRegularExpression* innerRegex = [[NSRegularExpression alloc] initWithPattern:@"href=\"(.*?)\"" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil]; 
NSTextCheckingResult* firstMatch = [innerRegex firstMatchInString:imageHtml options:0 range:NSMakeRange(0, [imageHtml length])]; 
[innerRegex release]; 

if(firstMatch != nil) 
{ 
    newImage.detailsURL = 
    NSLog(@"found url: %@", [imageHtml substringWithRange:firstMatch.range]); 
} 

它列出的唯一的事情就是全場比賽(這樣:HREF =「http://tralalala.com」,而不是http://tralalala.com

我怎樣才能迫使它只能退回我的第一個捕獲的括號匹配?

回答

6

正則表達式組由組0捕捉整場比賽的工作,然後在正則表達式的所有組將開始索引1 NSTextCheckingResult存儲這些羣體的範圍。由於您的正則表達式至少需要一個組,因此以下內容將起作用。

NSString *imageHtml = @"href=\"http://tralalala.com\""; //a string with some HTML in it 

NSRegularExpression* innerRegex = [[NSRegularExpression alloc] initWithPattern:@"href=\"(.*?)\"" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil]; 
NSTextCheckingResult* firstMatch = [innerRegex firstMatchInString:imageHtml options:0 range:NSMakeRange(0, [imageHtml length])]; 
[innerRegex release]; 

if(firstMatch != nil) 
{ 
    //The ranges of firstMatch will provide groups, 
    //rangeAtIndex 1 = first grouping 
    NSLog(@"found url: %@", [imageHtml substringWithRange:[firstMatch rangeAtIndex:1]]); 
} 
+0

太棒了!這正是我所期待的。 – 2011-05-06 07:40:32

0

您需要的模式是這樣的:

(?<=href=\")(.*?)(?=\") 
+0

這個前瞻和後面斷言的技巧很好。謝謝。我仍然有興趣知道如何訪問可能使用圓括號表示的各個組(例如,如果我指定了3個我感興趣的組...我如何訪問這些組) – 2011-05-06 07:14:39

+0

$ 1,$ 2,$ 3等。整個比賽可以以$ 0組的形式訪問。所以在你的情況下,你需要檢索$ 1(第一個顯式組)。 $ 0將是整場比賽。往前看,看後面不完全是羣,你不能訪問它們。 – dhblah 2011-05-06 08:32:47