我需要提取由两个字符(或两个标签)包围的所有字符串
这是我到目前为止所做的:
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]);
Run Code Online (Sandbox Code Playgroud)
在myArray中有正确的三个对象,但NSlog打印出来:
<NSSimpleRegularExpressionCheckingResult: 0x926ec30>{0, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb30>{6, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb50>{12, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
Run Code Online (Sandbox Code Playgroud)
而不是db1,db2和db3
哪里我错了?
Joe*_*Joe 20
根据文档 matchesInString:options:range:返回一个NSTextCheckingResult不是NSStrings 的数组.您将需要循环结果并使用范围来获取子字符串.
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]);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7132 次 |
| 最近记录: |