说给出一个NSString:
@"[myLabel]-10-[youImageView]"
我需要一个数组:
@[@"myLabel", @"yourImageView"]
我该怎么做?
我想通过字符串并检查每个'['和']',在其中获取字符串,但还有其他更好的方法吗?
由于
答案 0 :(得分:2)
您可以使用正则表达式:
NSString *string = @"[myLabel]-10-[youImageView]";
// Regular expression to find "word characters" enclosed by [...]:
NSString *pattern = @"\\[(\\w+)\\]";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSMutableArray *list = [NSMutableArray array];
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in the string:
NSRange range = [result rangeAtIndex:1];
[list addObject:[string substringWithRange:range]];
}
];
NSLog(@"%@", list);
输出:
( myLabel, youImageView )
答案 1 :(得分:0)
这对你有用吗?
NSCharacterSet *aSet = [NSCharacterSet characterSetWithCharactersInString:@"]-10["];
NSArray *anArray = [aString componentsSeparatedByCharactersInSet:aSet];