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

标签 iphone regex ios

尝试使用“捕获括号”从我正在解析(在 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/

相关文章:

ios - GTMOAuthViewControllerTouch 和 LinkedIn 注销

iphone - 修补 AFJSONRequestOperation 以在运行前检查变量?

iphone - 我的iPhone应用程序查看页面上的“报告问题”链接?

java - 正则表达式删除 Eclipse java 中 XML 文件中的注释

正则表达式从未知长度的单词字符串的末尾修剪空格

php - JavaScript 中的正则表达式修饰符/u?

ios - 使用 Swift 解压一个 zip 文件

ios - 使用命令行(openssl)验证iTunes iOS应用内收据(购买信息和签名)

iphone - iOS解析: string is null

iphone - 我可以使用 Objective-C block 并仍然在 iOS 4 之前的设备上运行吗?