我正在構建Twitter iPhone應用程序,它需要檢測何時在UITextView中的字符串中輸入hashtag或@ -mention。如何檢測在NSString中以「@」或「#」開頭的單詞?
如何在NSString中查找以「@」或「#」字符開頭的所有單詞?
感謝您的幫助!
我正在構建Twitter iPhone應用程序,它需要檢測何時在UITextView中的字符串中輸入hashtag或@ -mention。如何檢測在NSString中以「@」或「#」開頭的單詞?
如何在NSString中查找以「@」或「#」字符開頭的所有單詞?
感謝您的幫助!
您可以使用NSRegularExpression類,其類似於#\ w +(\ w代表單詞字符)。
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);
}
if([[test substringToIndex:1] isEqualToString:@"@"] ||
[[test substringToIndex:1] isEqualToString:@"#"])
{
bla blah blah
}
在做子串操作之前,不要忘記檢查文本是否長於1。否則,一些用戶會輸入一個空的消息,並在應用程序崩潰時生氣。 – 2012-05-01 10:35:33
可以突破使用componentsSeparatedByString字符串成片(字),然後檢查每個人的第一個字符。
或者,如果您需要在用戶輸入時執行此操作,則可以爲文本視圖提供委託並實現textView:shouldChangeTextInRange:replacementText:以查看輸入的字符。
定義字邊界始終是特定於應用程序的。 componentsSeparatedByString:是一種體面的技術,但程序員仍然需要做出「或/或」,「A1」和「新保守」以及其他一些結構的決定。 – 2012-04-27 16:14:16
在下面執行類似的操作。儘管你已經有了關於單詞界限的一點。人們可以想象,我喜歡/#這樣的#標籤這樣的標籤。嗯.... – n13 2014-03-30 15:57:22
爲此做了一個NSString的類別。這很簡單:查找所有單詞,返回以#開頭的所有單詞以獲取標籤。下面
相關代碼段 - 重命名這些方法&太種類...
@implementation NSString (PA)
// all words in a string
-(NSArray *)pa_words {
return [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
// only the hashtags
-(NSArray *)pa_hashTags {
NSArray *words = [self pa_words];
NSMutableArray *result = [NSMutableArray array];
for(NSString *word in words) {
if ([word hasPrefix:@"#"])
[result addObject:word];
}
return result;
}
這裏是如何使用NSPredicate
您可以嘗試在UITextView的代表是這樣做的:
- (void)textViewDidChange:(UITextView *)textView
{
_words = [self.textView.text componentsSeparatedByString:@" "];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] '@'"];
NSArray* names = [_words filteredArrayUsingPredicate:predicate];
if (_oldArray)
{
NSMutableSet* set1 = [NSMutableSet setWithArray:names];
NSMutableSet* set2 = [NSMutableSet setWithArray:_oldArray];
[set1 minusSet:set2];
if (set1.count > 0)
NSLog(@"Results %@", set1);
}
_oldArray = [[NSArray alloc] initWithArray:names];
}
其中_words,_searchResults和_oldArray是NSArrays。
使用下面的表達式
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(#(\\w+)|@(\\w+)) " options:NSRegularExpressionCaseInsensitive error:&error];
你需要編輯期間或編輯後能得到這些字符(可能通過調用一個動作)來檢測串@或#?根據這一點,我可以幫你 – ilhnctn 2012-04-27 15:39:43