从字符串中获取用户名的正则表达式

Regular expression to grub usernames from string

我需要在字符串中查找用户名(如 twitter 用户名),例如,如果字符串是:

"Hello, @username! How are you? And @username2??"

我想 isolate/extract @username@username2

你知道如何在 Objective-C 中做到这一点吗,我为 Python regex for Twitter username 找到了这个,但对我不起作用

我这样试过,但没有用:

NSString *comment = @"Hello, @username! How are you? And @username2??";

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(?<=^|(?<=[^a-zA-Z0-9-\.]))@([A-Za-z]+[A-Za-z0-9-]+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:comment options:0 range:NSMakeRange(0, comment.length)];
for (NSTextCheckingResult *match in matches) {
    NSRange wordRange = [match rangeAtIndex:1];
    NSString *username = [comment substringWithRange:wordRange];
    NSLog(@"searchUsersInComment result --> %@", username);
}

(?<=^|(?<=[^a-zA-Z0-9-\.]))@([A-Za-z]+[A-Za-z0-9-]+) 是忽略电子邮件并只获取用户名,因为您的字符串不包含任何电子邮件,您应该只使用 @([A-Za-z]+[A-Za-z0-9-]+)

你的正则表达式是错误的。您需要修改为:

  NSString *comment = @"Hello, @username! How are you? And @username2??";

    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"@([A-Za-z]+[A-Za-z0-9-]+)" options:0 error:&error];
    NSArray *matches = [regex matchesInString:comment options:0 range:NSMakeRange(0, comment.length)];
    for (NSTextCheckingResult *match in matches) {
        NSRange wordRange = [match rangeAtIndex:1];
        NSString *username = [comment substringWithRange:wordRange];
        NSLog(@"searchUsersInComment result --> %@", username);
    }

仅供参考:一对括号内的任何子模式都将被捕获为一个组。实际上,这可用于从各种数据中提取 phone 号码或电子邮件等信息。 想象一下,例如,您有一个命令行工具来列出您在云中拥有的所有图像文件。然后,您可以使用 ^(IMG\d+.png)$ 等模式来捕获和提取完整文件名,但如果您只想捕获不带扩展名的文件名,则可以使用模式 ^(IMG\d+).png$ 只截取句号前的部分.

我建议您阅读有关正则表达式字符串的内容:http://regexone.com/lesson/capturing_groups