如何检测 NSString 中以“@"或“#"开头的单词? [英] How do you detect words that start with “@” or “#” within an NSString?
本文介绍了如何检测 NSString 中以“@"或“#"开头的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个 Twitter iPhone 应用程序,它需要检测您何时在 UITextView 的字符串中输入主题标签或 @-mention.
I'm building a Twitter iPhone app, and it needs to detect when you enter a hashtag or @-mention within a string in a UITextView.
如何查找 NSString 中以@"或#"字符开头的所有单词?
How do I find all words preceded by the "@" or "#" characters within an NSString?
感谢您的帮助!
推荐答案
您可以使用 NSRegularExpression 类,其模式类似于 #w+(w 代表单词字符).
You can use NSRegularExpression class with a pattern like #w+ (w stands for word characters).
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [string substringWithRange:wordRange];
NSLog(@"Found tag %@", word);
}
这篇关于如何检测 NSString 中以“@"或“#"开头的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文