在iPhone上使用正则表达式捕获括号

3

我正在解析一些HTML(在iPhone上),尝试从中获取URL,使用“捕获括号”只分组我感兴趣的部分。

现在我有这个:

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)。如何强制它仅返回我的第一个捕获括号匹配?
2个回答

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
你需要类似这样的模式:
(?<=href=\")(.*?)(?=\")

这个使用前瞻和后顾断言的技巧效果很好。谢谢。我仍然想知道如何访问使用括号指定的各个组(例如,如果我指定了3个组,我如何访问这些组)。 - The dude
$1、$2、$3等仍然可以作为一个组来访问整个匹配项,即$0。在您的情况下,您需要检索$1(第一个显式组)。$0将是整个匹配项。前瞻和后顾不完全是组,您无法访问它们。 - dhblah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接