/ / Rileva hashtag che includono & in hashtag - ios, objective-c

Rileva hashtag che includono & in hashtag - ios, ogg-c

Posso rilevare hashtag come questo.

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

Il problema è che se inputStr è "# D & D", può rilevare solo #D. Come devo fare?

risposte:

1 per risposta № 1

Per questo con la tua espressione reg aggiungi un carattere speciale che vuoi consentire.

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

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

Allo stesso modo aggiungi altri caratteri speciali che desideri.

Quindi cambia semplicemente la tua espressione regolare in questo modo.

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

1 per risposta № 2

Stavo usando questa lib: https://cocoapods.org/pods/twitter-text

C'è una classe TwitterText con metodo (NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap Potrebbe aiutare.

Ho usato questo pod l'anno scorso, poi ha funzionato alla grande. Per oggi è necessario verificare se è ancora ok. Fammi sapere :) Buona fortuna