正则表达式从字符串grub用户名

时间:2016-06-08 15:20:15

标签: objective-c regex nsstring nsregularexpression

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

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

我想隔离/提取@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);
}

1 个答案:

答案 0 :(得分:1)

(?<=^|(?<=[^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);
    }

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

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