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

出力:

(
    myLabel、
    youImageView
)
于 2013-09-18T07:24:00.443 に答える