使用NSRegularExpression查找并检测“@”和“#”

时间:2014-05-14 10:14:05

标签: ios regex nsregularexpression

我试图在NSRegularExpression这样的文字中找到“@”和“#”符号;

NSString *testString = @"This text contains @ and # signs";
NSRange stringRange = NSMakeRange(0, [testString length]);
NSRegularExpression *regexTest = [[NSRegularExpression alloc] initWithPattern:@"\\b(@|#)\\b"];
NSRange nameRange = [regexTest rangeOfFirstMatchInString:testString options:0 range:stringRange];

当我NSLog nameRange.location时,它总是返回0.用NSRegularExpression找到这些符号的正确表格是什么?

1 个答案:

答案 0 :(得分:1)

这是我使用NSPredicate完成的方式。这会告诉您正在编辑/输入的当前@mention字。希望这会有所帮助。

- (void)textViewDidChange:(UITextView *)textView
{
    _words = [self.textView.text componentsSeparatedByString:@" "];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] '@'"];
    NSArray* names = [_words filteredArrayUsingPredicate:predicate];
    if (_oldArray)
    {
        NSMutableSet* set1 = [NSMutableSet setWithArray:names];
        NSMutableSet* set2 = [NSMutableSet setWithArray:_oldArray];
        [set1 minusSet:set2];
        if (set1.count > 0)
            NSLog(@"Results %@", set1);
    }
    _oldArray = [[NSArray alloc] initWithArray:names];
}