7

我需要提取由两个字符(或者可能是两个标签)包围的所有字符串

这是我到目前为止所做的:

    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

我哪里错了?

4

2 回答 2

20

根据文档 返回一个s 不是smatchesInString:options:range:的数组。您将需要遍历结果并使用范围来获取子字符串。NSTextCheckingResultNSString

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]);
}
于 2012-12-04T16:25:32.093 回答
0

或这个

NSArray *results = [@"[db1]+[db2]+[db3]" matchWithRegex:@"\\[(.*?)\\]"];

//result = @["db1","db2,"db3"]

与此类别https://github.com/damienromito/NSString-Matcher

于 2015-01-29T15:40:49.537 回答