如何在NSString中检测以“@”或“#”开头的单词? [英] How do you detect words that start with “@” or “#” within an NSString?

查看:115
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆