本文介绍了正则表达式提取两个字符或标签之间的所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要提取由两个字符(或者可能是两个标签)包围的所有字符串
I need to extract all the strings surrounded by two characters (or maybe two tags)
这是我到目前为止所做的:
this is what I've done so far:
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 打印:
In myArray there are correctly three objects but NSlog prints this:
<NSSimpleRegularExpressionCheckingResult: 0x926ec30>{0, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb30>{6, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
<NSSimpleRegularExpressionCheckingResult: 0x926eb50>{12, 5}{<NSRegularExpression: 0x926e660> \[(.*?)\] 0x1}
代替 db1、db2 和 db3
instead of db1, db2 and db3
我错在哪里?
推荐答案
根据文档 matchesInString:options:range:
返回一个数组 NSTextCheckingResult
s 不是 NSString
s.您需要遍历结果并使用范围来获取子字符串.
According to the documentation matchesInString:options:range:
returns an array of NSTextCheckingResult
s not NSString
s. 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]);
}
这篇关于正则表达式提取两个字符或标签之间的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!