I’m terrible with RegEx and found this bit somewhere on the interwebs. It’s for matching Twitter-style @username but it has one small problem – it also accepts a space as a word.
NSRegularExpression *atRegex = [NSRegularExpression regularExpressionWithPattern:@"(?<!\\w)@([\\w\\._-]+)?" options:NSRegularExpressionCaseInsensitive error:&error];
Example: “@erik” is matched correctly, but “@ erik” is also matched and should not be.
Your regular expression contains
The
?at the end means that everything inside the preceding(...)is completely optional. So, your regex doesn’t have to match anything following a @.To fix this, you may be able to remove the
( )?, leaving:However, you should also investigate what that
(?<!\\w)is doing for you and whether you need it.