NSString が与えられたとします。
@"[myLabel]-10-[youImageView]"
次の配列が必要です。
@[@"myLabel", @"yourImageView"]
どうすればいいのですか?
文字列を調べて、それぞれの '[' と ']' をチェックして、その中の文字列を取得することを考えましたが、他に良い方法はありますか?
ありがとう
NSString が与えられたとします。
@"[myLabel]-10-[youImageView]"
次の配列が必要です。
@[@"myLabel", @"yourImageView"]
どうすればいいのですか?
文字列を調べて、それぞれの '[' と ']' をチェックして、その中の文字列を取得することを考えましたが、他に良い方法はありますか?
ありがとう
正規表現を使用できます。
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 )