2

假设给定一个 NSString:

@"[myLabel]-10-[youImageView]"

我需要一个数组:

@[@"myLabel", @"yourImageView"]

我该怎么做?

我想过遍历字符串并检查每个'['和']',在其中获取字符串,但是还有其他更好的方法吗?

谢谢

4

2 回答 2

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

输出:

(
    我的标签,
    你的ImageView
)
于 2013-09-18T07:24:00.443 回答
0

这对你有用吗?

NSCharacterSet *aSet = [NSCharacterSet characterSetWithCharactersInString:@"]-10["];
NSArray *anArray = [aString componentsSeparatedByCharactersInSet:aSet];
于 2013-09-18T07:18:21.657 回答