您应该使用正则表达式:
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
编辑要获取包含除标签之外的输入字符串的字符串,可以使用以下方法:
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);