2011-12-12 89 views
0

我正在开发一个iPhone应用程序,它将使用NSRegularExpression来匹配来自字符串的模式以提取信息。这里我试图从电子邮件标题中提取mailTo链接。我已经成功地检索了电子邮件标题字符串,现在我正在使用NSregularExpression应用搜索模式来从标题字符串中获取电子邮件标识。无法使用NSRegularExpression提取信息

这是从哪儿我想提取的mailto的标题文字:

List-Unsubscribe: <mailto:[email protected]n>?subject=Unsubscribe>,<http://suksh.mailserv.in/suksh/?p=unsubscribe&mid=5451&uid=d8135921c2e2d40400ab02fa31eda529>>

这是搜索模式:

mailto:(?<address>[^\?^>]+)\??(?<params>[^>]+)? 

我的代码是这样的

NSString *str= @"List-Unsubscribe: <mailto:[email protected]n>?subject=Unsubscribe>,<http://suksh.mailserv.in/suksh/?p=unsubscribe&mid=5451&uid=d8135921c2e2d40400ab02fa31eda529>>"; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"mailto:(?<address>[^\?^>]+)\??(?<params>[^>]+)?"]; 
NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:str options:0 range:NSMakeRange(0, [str length])]; 

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { 
    NSString *substringForFirstMatch = [str substringWithRange:rangeOfFirstMatch]; 
    NSLog(@"Extracted URL: %@",substringForFirstMatch); 
} 

但当我要在regularExpressionWithPattern:的帮助下创建NSRegularExpression对象时,它返回nil o bject。

请帮助我什么是问题。

预先感谢

+0

不知道这是否是唯一的问题,但你还没有逃过正则表达式中的反斜杠。 – omz

+0

此外,没有'regularExpressionWithPattern:'方法,它被称为'regularExpressionWithPattern:options:error:','error'参数应该会让你知道你的表达有什么问题。 – omz

回答

1

的图案列将被处理两次:一次由编译器,然后通过NSRegularExpression。您必须转义反斜杠以确保编译器不会处理每个“\?”。

NSRegularExpressionICU文档均未提及对命名捕获组的支持((?<name>pattern));这可能会导致模式解析失败或匹配失败。

当您创建正则表达式时使用regularExpressionWithPattern:options:error:,因此您可以获得error对象,该对象将告诉您为什么构建失败。

NSError *theError; 
// '?\?(' is to prevent '??(' from being interpreted as a trigraph 
NSString *pattern = @"mailto:(?<address>[^\\?^>]+)\\?\?(?<params>[^>]+)?"; 
NSRegularExpression *regex; 
NSRange rangeOfFirstMatch; 

regex = [NSRegularExpression regularExpressionWithPattern:pattern 
      options:0 error:&theError]; 
if (regex) { 
    rangeOfFirstMatch = [regex rangeOfFirstMatchInString:str 
          options:0 range:NSMakeRange(0, [str length])]; 

    if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { 
     NSString *substringForFirstMatch = [str substringWithRange:rangeOfFirstMatch]; 
     NSLog(@"Extracted URL: %@",substringForFirstMatch); 
    } 
} else { 
    // couldn't compile RE 
    NSAlert *errorAlert; 
    if (theError) { 
     errorAlert = [NSAlert alertWithError:theError]; 
    } else { 
     NSString *errorMsg = @"Couldn't parse unsubscribe header because the pattern /%@/ isn't a valid regular expression."; 
     errorAlert = [NSAlert 
       alertWithMessageText:@"Invalid Pattern" 
         defaultButton:nil 
         alternateButton:nil 
          otherButton:nil 
      informativeTextWithFormat:[NSString stringWithFormat:errorMsg, pattern]]; 
    } 
    [theAlert runModal]; // Ignore return value. 
}