Question

I am trying to find "@" and "#" sign in my text with NSRegularExpression like that;

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];

When i NSLog nameRange.location, it's always return 0. What is the correct form to find that signs with NSRegularExpression?

Was it helpful?

Solution

This is how I did it using NSPredicate. This tells you the current @mention word that's being edited/typed. Hope this helps.

- (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];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top