2017-02-09 123 views
0

我可以检测这样的标签。检测#标签包括&#标签

+ (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。我该怎么办?

+0

它可能会帮助http://stackoverflow.com/questions/7934688/how-to-see-if-an-nsstring-starts-with-a-certain-other-string – raki

回答

1

对于你的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]; 
+2

什么关于'D&D&D'? :)提示,括号会有所帮助。 – Sulthan

+0

@Sulthan Thanx的建议,也编辑答案。 –

1

我就是用这个LIB: https://cocoapods.org/pods/twitter-text

没有与方法 (NSArray *)hashtagsInText:(NSString *)text checkingURLOverlap (BOOL)checkingURLOverlap TwitterText类它可以帮助。

我上一次使用这个pod,那么它工作得很好。今天你需要检查它是否仍然可以。让我知道:)祝你好运