尝试使用“捕获括号”从我正在解析(在 iPhone 上)的某些 HTML 中获取 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://traralala.com"而不是 http://tralalala.com
我怎样才能强制它只返回我的第一个捕获括号匹配项?
最佳答案
正则表达式组通过捕获组 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]]);
}
关于iphone - 在 iphone 上使用正则表达式捕获括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5898998/