ios - 合并两个 NSRegularExpression

标签 ios objective-c

我想将 stringWithHashtags 中的每个单词添加到以 @# 开头的 attString 中.我认为最简单的方法是合并两个 NSRegularExpression 然后将其分配给数组。实际上我是这样依次分配它们的:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];

NSRegularExpression *regexM = [NSRegularExpression regularExpressionWithPattern:@"@(\\w+)" options:0 error:&error];

NSArray *matches = [regex matchesInString:stringWithHashtags options:0 range:NSMakeRange(0, stringWithHashtags.length)];
matches = [regexM matchesInString:stringWithHashtags options:0 range:NSMakeRange(0, stringWithHashtags.length)];

在结果中只有提及是蓝色的。(它只适用于主题标签)

这是我的完整方法:

-(NSMutableAttributedString*)detectHashtags:(NSString *)stringWithHashtags{

    NSError *error = nil;

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];

    NSRegularExpression *regexTag = [NSRegularExpression regularExpressionWithPattern:@"@(\\w+)" options:0 error:&error];

    NSArray *matches = [regex matchesInString:stringWithHashtags options:0 range:NSMakeRange(0, stringWithHashtags.length)];
    matches = [regexTag matchesInString:stringWithHashtags options:0 range:NSMakeRange(0, stringWithHashtags.length)];

    NSMutableAttributedString *attString= [[NSMutableAttributedString alloc] initWithString:stringWithHashtags];

    NSInteger stringLength= [stringWithHashtags length];

    for (NSTextCheckingResult *match in matches) {

        NSRange wordRange = [match rangeAtIndex:0];
        NSString* word = [stringWithHashtags substringWithRange:wordRange];

        UIColor *foregroundColor=[UIColor blueColor];
        [attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];

    }
    UIFont *font=[UIFont fontWithName:@"Helvetica" size:13.0f];
    [attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, stringLength)];

    return attString;
}

是否有可能以某种方式合并 regexregexTag

最佳答案

您是否考虑过合并正则表达式模式而不是 NSRegularExpression 实例?

给定 re1re2 然后模式 (re1)|(re2) 匹配它们中的任何一个。例如,#|@ 匹配 # 或 @。您还可以使用 [characters in set] 匹配一组字符中的一个。

HTH

关于ios - 合并两个 NSRegularExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27473442/

相关文章:

ios - 将参数传递给实现协议(protocol)并快速扩展类的方法

objective-c - 桥接 Swift 和 Objective-C 不能完全工作

ios - WKWebView的标题等于document.title?

ios - Xcode 4.5 项目警告 - "Upgrade Compiler configuration to LLVM"

ios - Xcode Interface Builder 为所有文件显示 "No selection"

ios - Swift UITextField adjustmentFontSizeToFitWidth 无法正常工作

objective-c - NSToolbar 项中的 NSButton : click issue

objective-c - 来自 Objective-C 协议(protocol)的 Swift 扩展

objective-c - 真的卡在屏幕旋转 iOS 6 上,我需要一个锁定到纵向的 xib

ios - UIPickerView 设置选定行的背景颜色(现在也适用于 iOS 14)