简体   繁体   中英

NSRegularExpression: How to match word starting with @

I'd like to convert references to usernames such as @me, @you, @them (twitter style) to links. What would be the correct NSRegularExpression pattern for this?


Based on the input from answers below, here's what I ended up using...

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<!\\w)@([\\w\\._-]+)?" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *newString = [regex stringByReplacingMatchesInString:stringIn options:0 range:NSMakeRange(0, [stringIn length]) withTemplate:@"<a href='http://mydomain.com/$1'>$0</a>"];

This may not be a perfect match for Twitter, as my own site supports dots, dashes and underlines

(?<!\w)@\w+ should be pretty safe.

The (?<!\w) is called a Negative Lookbehind and makes sure there's no word character before the @, preventing to match email addresses.

@[a-zA-Z0-9_]+ should get the job done pretty well.

I would recommend throwing some test data in RegExr and fiddling with the regex to match exactly what you need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM