NSString * str = @" Hello {{{separate this}}}以及此{{{也将此}}}}世界"
我需要输出数组:
hello :在数组中的索引0
将此:分隔在数组
中的索引1处以及:在数组中的索引2
还将此:分隔在数组中的索引3
世界:在数组中的索引4
答案 0 :(得分:0)
NSString *str = @"Hello group1 group1 group1 and also this group2 group2 group2 world";
NSString *pattern = @"^Hello (.+) and also this (.+) world$";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionSearch
error:nil];
NSArray *matches = [regex matchesInString:str
options:0
range:NSMakeRange(0, [str length])];
if ([matches count] == 2) {
NSString *group1 = [str substringWithRange:[matches[0] range]];
NSString *group2 = [str substringWithRange:[matches[1] range]];
} else {
NSLog(@"Match failed");
}
答案 1 :(得分:0)
下面的代码会为您提供相关指定的结果。
请注意!!! - 此代码仅适用于您在问题{{{
和}}}
中提及的静态符号组合。如果在该组合中进行的任何更改,您将无法获得所需的结果。
NSString *str = @"Hello {{{sepearte this}}} and also this {{{ also seperate this}}} world";
str = [str stringByReplacingOccurrencesOfString:@" {{{" withString:@"#"];
str = [str stringByReplacingOccurrencesOfString:@"}}} " withString:@"#"];
NSArray *components = [str componentsSeparatedByString:@"#"];
答案 2 :(得分:0)
假设您的字符串格式正确,即没有任何不平衡的大括号,您可以拆分大括号:
NSArray<NSString *> *components = [[str stringByReplacingOccurrencesOfString:@"}}}" withString:@"{{{"] componentsSeparatedByString:@"{{{"];
然后最终修剪结果字符串:
NSMutableArray<NSString *> *trimmedComponents = [NSMutableArray array];
for (NSString *component in components) {
[trimmedComponents addObject:[component stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]];
}