2011-01-12 32 views
3

我想提取括号无法提取使用NSRegularExpression(正则表达式模式)串 - iphone

实施例 原始字符串之间[]字符串:@“这是一个测试[得到这个字符串]”。

我想在[]之间得到提取字符串,即“在此示例中获取此字符串”。

请在下面找到我的代码

NSMutableString *predicateString = [[NSMutableString alloc] initWithFormat:@"%@",@"this is a test [to get this string]."]; 

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\[[^\].]*\]" 
        options:NSRegularExpressionCaseInsensitive 
        error:&error]; 


NSMutableArray *rangeArray = [[NSMutableArray alloc] init]; 
__block NSUInteger count = 0; 
[regex enumerateMatchesInString:predicateString options:0 range:NSMakeRange(0, [predicateString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){ 
    NSRange matchRange = [match range]; 
    matchRange.length = matchRange.length+1; 
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; 
    NSLog(@"matchRange.location: %d",matchRange.location); 
    NSLog(@"matchRange.length: %d",matchRange.length); 

    if (++count >= 100) *stop = YES; 

}]; 

请让我知道,如果我做错了什么。

谢谢。

回答

1

看起来表达式是错误的,您需要跳过斜线(例如:@"\\[[^\\].]*\\]")。

+0

感谢马塞洛.....它工作。 – D25 2011-01-12 14:13:05