ios - 使用2种模式时遇到正则表达式问题

标签 ios objective-c regex nsregularexpression

我有一个在UITextView更新期间调用的方法,该方法可以帮助我检测井号和用户名提及。 #hashtag@username
如果我一次只尝试检测一个,那么此代码可以完美地工作。我可以仅检测主题标签,也可以仅检测用户名提及。

我正在尝试使其能够同时检测到两者。

这是我的两个正则表达式模式:

  • 标签:#(\\w+)
  • 用户名:@(\\w+)

  • 这是我的检测方法:
    - (NSMutableAttributedString*)decorateTags:(NSString *)stringWithTags{
    
    NSError *error = nil;
    
    // Hashtag detection
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+) | @(\\w+)" options:0 error:&error];
    
    NSArray *matches = [regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
    NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];
    
    NSInteger stringLength = [stringWithTags length];
    
    for (NSTextCheckingResult *match in matches) {
    
        NSRange wordRange = [match rangeAtIndex:0];
    
        NSString* word = [stringWithTags substringWithRange:wordRange];
    
        // Set Foreground Color
        UIColor *foregroundColor = [UIColor blueColor];
        [attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];
    
        NSLog(@"Found tag %@", word);
    
      }
       return attString;
    }
    

    上面的代码可以完美地工作,但是就像我说的那样,它目前仅设置为一次检测一个。因此,我修改了regex模式以搜索主题标签和用户名提及内容,并尝试使用|, +, *, *+, ++, +,等几种运算符,但它们都不允许同时检测主题标签和用户名,但要明确一下,这是我的意思:

    “嘿 @John 看看这个 #hashtag

    看看两者如何突出显示?这就是我所需要的,但是在使用Apple regex文档中提供的运算符进行测试之后,我只能突出显示一个,或者根本不突出显示。

    例如,使用上面的示例代码,#hashtag将突出显示,但@John将不突出显示。

    以下是一些有关如何尝试使用运算符的快速示例:
    [NSRegularExpression regularExpressionWithPattern:@"#(\\w+) + @(\\w+)" options:0 error:&error];
    
    [NSRegularExpression regularExpressionWithPattern:@"#(\\w+) | @(\\w+)" options:0 error:&error];
    
    [NSRegularExpression regularExpressionWithPattern:@"#(\\w+) * @(\\w+)" options:0 error:&error];
    

    最佳答案

    您使用的正则表达式仅与第一个匹配。如果在开始迭代之前设置了断点,则会看到匹配计数为1。

    第二件事不匹配的原因是因为计算了|周围的空格。

    在这种情况下,可以使用像(#|@)(\\w+)这样的正则表达式。我设置了一个示例项目来测试此正则表达式,它可以正常工作。

    关于ios - 使用2种模式时遇到正则表达式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29595496/

    相关文章:

    ios - UICollectionView 比 NavigationController 大

    javascript - Cordova InAppBrowserexecuteScript() 未在 iOS 中触发回调

    ios - NSFetchedResultsController 似乎正在将空对象插入数组?

    iphone - 在谓词中使用@min、@max 等?

    python - 正则表达式,用空格替换所有下划线和特殊字符?

    python - 提取文本与正则表达式匹配的 URL - 使用 XPath 1.0

    ios - 在 App Store 中更改支持语言的 iOS 应用程序列表

    iOS多步表单

    objective-c - 在 Objective-C 中返回后,代码最终会运行吗?

    Java 正则表达式查找末尾没有 = 的单词