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

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]);

在我的数组中有三个对象,但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个回答

20
根据文档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]);
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接