2012-12-04 63 views
7

我需要提取兩個字符(或者兩個標記)包圍的所有字符串正則表達式來提取全2個charachters或標記之間的子

這是我迄今所做的:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL]; 

    NSArray *myArray = [regex matchesInString:@"[db1]+[db2]+[db3]" options:0 range:NSMakeRange(0, [@"[db1]+[db2]+[db3]" length])] ; 

    NSLog(@"%@",[myArray objectAtIndex:0]); 
    NSLog(@"%@",[myArray objectAtIndex:1]); 
    NSLog(@"%@",[myArray objectAtIndex:2]); 

在myArray的有正確的三個對象,但NSLog的打印這樣的:

<NSSimpleRegularExpressionCheckingResult: 0x926ec30>{0, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} 
<NSSimpleRegularExpressionCheckingResult: 0x926eb30>{6, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} 
<NSSimpleRegularExpressionCheckingResult: 0x926eb50>{12, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1} 

代替DB1,DB2和DB3

我錯了?

謝謝

回答

20

按照documentationmatchesInString:options:range:回報NSTextCheckingResult數組不是NSString秒。您需要遍歷結果並使用範圍來獲取子字符串。

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\[(.*?)\\]" options:NSRegularExpressionCaseInsensitive error:NULL]; 

NSString *input = @"[db1]+[db2]+[db3]"; 
NSArray *myArray = [regex matchesInString:input options:0 range:NSMakeRange(0, [input length])] ; 

NSMutableArray *matches = [NSMutableArray arrayWithCapacity:[myArray count]]; 

for (NSTextCheckingResult *match in myArray) { 
    NSRange matchRange = [match rangeAtIndex:1]; 
    [matches addObject:[input substringWithRange:matchRange]]; 
    NSLog(@"%@", [matches lastObject]); 
} 
+0

OK,謝謝! – Janky