简体   繁体   中英

Detect hashtags including & in hashtag

I can detect hashtags like this.

+ (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;
}

Problem is that if inputStr is "#D&D", it can detect only #D. How shall I do?

For that with your reg expression add special character that you want allow.

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

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

Same way you add other special character that you want.

So simply change your regex like this.

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

I was using this lib: https://cocoapods.org/pods/twitter-text

There is TwitterText class with method (NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap It could help.

I used this pod year ago last time, then it worked great. For today you need to check if it is still ok. Let me know :) Good luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM