【问题标题】:Parse ANSI color codes and set the according color attributes for NSAttributedString解析 ANSI 颜色代码并为 NSAttributedString 设置相应的颜色属性
【发布时间】:2014-06-29 04:43:28
【问题描述】:

我需要一种方法来解析来自 shell 输出的 ANSI 颜色代码,以便为 NSAttributedString 设置相应的颜色属性。

输入字符串看起来像:

[0;31m 这应该是红色的。[0;34m 这应该是蓝色的。 [0;32m这应该是绿色的。[0;31m这也应该是红色的。

从输出中删除 Ansi 代码后,我的代码与颜色不匹配。我当前的代码如下:

- (NSAttributedString*)ansicodeParser:(NSString *)str
{
    // init string
    NSMutableString           *mutableStr    = [[NSMutableString alloc] initWithString:str];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc]initWithString:str];

    // set default text attributes
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0,[attributedStr length])];
    [attributedStr addAttribute:NSBackgroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,[attributedStr length])];


    // init ansiColors dict
    NSDictionary *ansiColors = @{
        // Resets
        @"\\[H"     : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // Text Reset
        @"\\[J"     : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // Text Reset
        @"\\[0m"    : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // Text Reset

        // Regular Text + Colors
        @"\\[0;30m" : @{ NSForegroundColorAttributeName : [UIColor blackColor] },    // Black
        @"\\[0;31m" : @{ NSForegroundColorAttributeName : [UIColor redColor] },      // Red
        @"\\[0;32m" : @{ NSForegroundColorAttributeName : [UIColor greenColor] },    // Green
        @"\\[0;33m" : @{ NSForegroundColorAttributeName : [UIColor yellowColor] },   // Yellow
        @"\\[0;34m" : @{ NSForegroundColorAttributeName : [UIColor blueColor] },     // Blue
        @"\\[0;35m" : @{ NSForegroundColorAttributeName : [UIColor purpleColor] },   // Purple
        @"\\[0;36m" : @{ NSForegroundColorAttributeName : [UIColor cyanColor] },     // Cyan
        @"\\[0;37m" : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // White

        // Bold Text + Colors
        @"\\[1;30m" : @{ NSForegroundColorAttributeName : [UIColor blackColor] },    // Black
        @"\\[1;31m" : @{ NSForegroundColorAttributeName : [UIColor redColor] },      // Red
        @"\\[1;32m" : @{ NSForegroundColorAttributeName : [UIColor greenColor] },    // Green
        @"\\[1;33m" : @{ NSForegroundColorAttributeName : [UIColor yellowColor] },   // Yellow
        @"\\[1;34m" : @{ NSForegroundColorAttributeName : [UIColor blueColor] },     // Blue
        @"\\[1;35m" : @{ NSForegroundColorAttributeName : [UIColor purpleColor] },   // Purple
        @"\\[1;36m" : @{ NSForegroundColorAttributeName : [UIColor cyanColor] },     // Cyan
        @"\\[1;37m" : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // White

        // Underlined Text + Colors
        @"\\[4;30m" : @{ NSForegroundColorAttributeName : [UIColor blackColor] },    // Black
        @"\\[4;31m" : @{ NSForegroundColorAttributeName : [UIColor redColor] },      // Red
        @"\\[4;32m" : @{ NSForegroundColorAttributeName : [UIColor greenColor] },    // Green
        @"\\[4;33m" : @{ NSForegroundColorAttributeName : [UIColor yellowColor] },   // Yellow
        @"\\[4;34m" : @{ NSForegroundColorAttributeName : [UIColor blueColor] },     // Blue
        @"\\[4;35m" : @{ NSForegroundColorAttributeName : [UIColor purpleColor] },   // Purple
        @"\\[4;36m" : @{ NSForegroundColorAttributeName : [UIColor cyanColor] },     // Cyan
        @"\\[4;37m" : @{ NSForegroundColorAttributeName : [UIColor whiteColor] },    // White

        // Background Colors
        @"\\[40m"   : @{ NSBackgroundColorAttributeName : [UIColor blackColor] },    // Black
        @"\\[41m"   : @{ NSBackgroundColorAttributeName : [UIColor redColor] },      // Red
        @"\\[42m"   : @{ NSBackgroundColorAttributeName : [UIColor greenColor] },    // Green
        @"\\[43m"   : @{ NSBackgroundColorAttributeName : [UIColor yellowColor] },   // Yellow
        @"\\[44m"   : @{ NSBackgroundColorAttributeName : [UIColor blueColor] },     // Blue
        @"\\[45m"   : @{ NSBackgroundColorAttributeName : [UIColor purpleColor] },   // Purple
        @"\\[46m"   : @{ NSBackgroundColorAttributeName : [UIColor cyanColor] },     // Cyan
        @"\\[47m"   : @{ NSBackgroundColorAttributeName : [UIColor whiteColor] },    // White
    };

    // set color attribute
    for(NSString *ansiStr in ansiColors)
    {
        // search ansicode in output
        NSRegularExpression *regex    = [NSRegularExpression regularExpressionWithPattern:ansiStr options:NSRegularExpressionCaseInsensitive error:nil];
        NSMutableArray      *matches  = (NSMutableArray*)[regex matchesInString:mutableStr options:0 range:NSMakeRange(0, mutableStr.length)];

        for (NSTextCheckingResult *match in matches)
        {
            // gather values
            NSRange wordRange   = [match rangeAtIndex:0];
            UIColor  *fontColor = [[ansiColors objectForKey:ansiStr] objectForKey:NSForegroundColorAttributeName];
            UIColor  *backColor = [[ansiColors objectForKey:ansiStr] objectForKey:NSBackgroundColorAttributeName];

            // set foreground color
            if(fontColor != nil)
                [attributedStr addAttribute:NSForegroundColorAttributeName value:fontColor range:NSMakeRange(wordRange.location+wordRange.length, [[[attributedStr mutableString] substringFromIndex:wordRange.location] length] - wordRange.length)];

            // set background color
            if(backColor != nil)
                [attributedStr addAttribute:NSBackgroundColorAttributeName value:backColor range:NSMakeRange(wordRange.location+wordRange.length, [[[attributedStr mutableString] substringFromIndex:wordRange.location] length] - wordRange.length)];
        }
    }

    // remove ansicodes from output
    for(NSString *ansiStr in ansiColors)
    {
        [[attributedStr mutableString] replaceOccurrencesOfString:[ansiStr substringFromIndex:1] withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, attributedStr.length)];
    }

    // return formatted console output
    return (NSAttributedString*)attributedStr;
}

【问题讨论】:

  • 颜色和 cmets 在您的代码中并不总是匹配:例如@"\\[0;30m" : [UIColor whiteColor], // Black...是白色还是黑色??
  • 是的,你是对的,它实际上是黑色的代码,但我将它的值设置为白色,因为默认字体颜色是白色,因此不应该支持黑色字体。
  • 什么,到底行不通?我在ls -G / 的输出上运行了你的代码,得到了imgur.com/9lMc0fO,它只检测到一个颜色代码(你的其他正则表达式都不匹配),但也成功地删除了它。

标签: ios objective-c shell terminal ansi-colors


【解决方案1】:

您需要以不同的方式处理它。 您不能设置属性范围,然后以这种方式修改字符串。这会改变属性的范围。 有很多方法可以做到这一点。 在不混淆的情况下,一种更简单的方法是首先根据匹配将字符串拆分为一个数组。 然后从数组中的每个字符串中删除 ANSI 颜色前缀并应用颜色。 然后将数组连接成一个字符串。

另一种方法是首先将未归属的字符串转换为另一种格式。 例如,它可以是 HTML 或 RTF。然后您要做的就是将 ANSI 颜色标签转换为可可文本系统已经可以为您处理的格式。

【讨论】:

  • 感谢您的建议,您可以举个例子吗?
  • 这篇文章展示了一个执行此操作的 Perl 模块。你可以在 Objective-c 中做同样的事情,因为 Perl 用正则表达式来做。 stackoverflow.com/questions/245121/…
  • 或者你可以只运行 Perl 脚本然后使用输出。
猜你喜欢
  • 1970-01-01
  • 2012-05-22
  • 2021-01-13
  • 2013-10-13
  • 1970-01-01
  • 2017-03-24
  • 2020-06-28
  • 1970-01-01
  • 2011-09-03
相关资源
最近更新 更多