正则表达式提取两个字符或标记之间的所有子字符串

时间:2012-12-04 16:17:12

标签: objective-c regex

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

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

    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

我哪里错了?

2 个答案:

答案 0 :(得分:20)

根据documentation matchesInString: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]);
}

答案 1 :(得分:0)

或者这个

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

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

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