2012-02-01 65 views
0

什么是将用户标识从以下格式的URL中拉出的正则表达式?例如。在下面的例子中,我想在应用正则表达式后得到“1227627”作为匹配。正则表达式从图形API URL获取Facebook用户ID?

https://graph.facebook.com/1227627/movies?access_token=[access_token]&limit=5000&offset=5000&__after_id=103108306395658

注:我将在iOS版/ Objective C的使用这个。

对于一些背景 - 我正在使用graphi API批处理请求。批量请求最多可以包含20个单独的请求,不幸的是,单个响应不会返回请求URL。我可以跟踪所有的个人请求,但解析出与请求相对应的用户标识会更简单。

回答

1

您可以使用'https?://graph.facebook.com/([0-9] +)/',号码将成为第一个捕获组。

东西线沿线的:

// input URL 
NSString *urlString = @"https://graph.facebook.com/1227627/movies?access_token=access_token]&limit=5000&offset=5000&__after_id=103108306395658"; 

// construct the regex 
NSRegularExpression *regex = [NSRegularExpression 
     regularExpressionWithPattern:@"https?://graph\\.facebook\\.com/([0-9]+)/" 
          options:NSRegularExpressionSearch 
          error:nil]; 
// match against url 
NSArray *matches = [regex matchesInString:urlString 
            options:0 
            range:NSMakeRange(0, [urlString length])]; 
// extract capturing group 1 
for (NSTextCheckingResult *match in matches) { 
    NSRange matchRange = [match rangeAtIndex:1]; 
    NSString *matchString = [urlString substringWithRange:matchRange]; 
    NSLog(@"%@", matchString); 
} 
+0

真棒,谢谢你,这么一个完整的answer--你有任何指针学习正则表达式? – ch3rryc0ke 2012-02-01 08:36:14