簡體   English   中英

檢測井號,包括井號中的&

[英]Detect hashtags including & in hashtag

我可以檢測到這樣的主題標簽。

+ (NSArray *)getHashArrayWithInputString:(NSString *)inputStr
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];

    NSArray *matches = [regex matchesInString:inputStr options:0 range:NSMakeRange(0, inputStr.length)];
    NSMutableArray *muArr = [NSMutableArray array];
    for (NSTextCheckingResult *match in matches) {
        NSRange wordRange = [match rangeAtIndex:1];
        NSString* word = [inputStr substringWithRange:wordRange];

        NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
        if ([word rangeOfCharacterFromSet:notDigits].location == NSNotFound)
        {
            // newString consists only of the digits 0 through 9
        }
        else
        [muArr addObject:[NSString stringWithFormat:@"#%@",word]];
    }
    return muArr;
}

問題是,如果inputStr為“#D&D”,則只能檢測到#D。 我該怎么辦?

為此,請使用reg表達式添加要允許的特殊字符。

#(\\w+([&]*\\w*)*) //To allow #D&D&d...

#(\\w+([&-]*\\w*)*) //To allow both #D&D-D&... 

添加所需的其他特殊字符的方式相同。

因此,只需像這樣更改您的正則表達式。

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+([&]*\\w*)*)" options:0 error:&error];

我正在使用這個庫: https : //cocoapods.org/pods/twitter-text

TwitterText類的方法是(NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap這可能有所幫助。

一年前我上次使用此Pod,但效果很好。 今天,您需要檢查是否還可以。 讓我知道:)祝你好運

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM