正規表現を使用する必要があります。
NSString *input = @"Something #hello #world";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#\\w+" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];
NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
NSString *tag = [input substringWithRange:[match range]];
NSLog(@"%@", tag);
}
// #hello
// #world
編集ハッシュ文字なしでタグを取得するには#
、次のように正規表現でキャプチャ グループを使用する必要があります。
NSString *input = @"Something #hello #world";
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"#(\\w+)" options:0 error:nil];
NSArray *matches = [regex matchesInString:input options:0 range:NSMakeRange(0, input.length)];
NSLog(@"%d matches found.", matches.count);
for (NSTextCheckingResult *match in matches) {
NSString *tag = [input substringWithRange:[match rangeAtIndex:1]];
NSLog(@"%@", tag);
}
// hello
// world
EDITタグを除く入力文字列を含む文字列を取得するには、次のメソッドを使用できます。
NSString *stringWithoutTags = [regex stringByReplacingMatchesInString:input options:0 range:NSMakeRange(0, input.length) withTemplate:@""];
NSLog(@"%@", stringWithoutTags);
// Something
編集さまざまなタグが用意されたので、次のようにそれらを含む文字列を作成できます。
NSMutableArray *tagsArray = [NSMutableArray array];
for (NSTextCheckingResult *match in matches) {
NSString *tag = [input substringWithRange:[match range]];
[tagsArray addObject:tag];
}
NSString *tagsString = [tagsArray componentsJoinedByString:@", "];
NSLog(@"tagsString: %@", tagsString);