简体   繁体   English

检测井号,包括井号中的&

[英]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. 问题是,如果inputStr为“#D&D”,则只能检测到#D。 How shall I do? 我该怎么办?

For that with your reg expression add special character that you want allow. 为此,请使用reg表达式添加要允许的特殊字符。

#(\\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 我正在使用这个库: https : //cocoapods.org/pods/twitter-text

There is TwitterText class with method (NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap It could help. TwitterText类的方法是(NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap这可能有所帮助。

I used this pod year ago last time, then it worked great. 一年前我上次使用此Pod,但效果很好。 For today you need to check if it is still ok. 今天,您需要检查是否还可以。 Let me know :) Good luck 让我知道:)祝你好运

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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