且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-11-12 11:43:50

根据文档 matchesInString:options:range: 返回一个数组 NSTextCheckingResults 不是 NSStrings.您需要遍历结果并使用范围来获取子字符串.

According to the documentation matchesInString:options:range: returns an array of NSTextCheckingResults not NSStrings. You will need to loop over the results and use the ranges to get the substrings.

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