草庐IT

ios - 解析 ANSI 颜色代码并为 NSAttributedString 设置相应的颜色属性

coder 2024-01-19 原文

我需要一种方法来解析 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;
}

最佳答案

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

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

关于ios - 解析 ANSI 颜色代码并为 NSAttributedString 设置相应的颜色属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23598549/

有关ios - 解析 ANSI 颜色代码并为 NSAttributedString 设置相应的颜色属性的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  3. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  6. ruby-on-rails - Rails 源代码 : initialize hash in a weird way? - 2

    在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has

  7. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  8. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  9. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  10. ruby-on-rails - 如何使用 instance_variable_set 正确设置实例变量? - 2

    我正在查看instance_variable_set的文档并看到给出的示例代码是这样做的:obj.instance_variable_set(:@instnc_var,"valuefortheinstancevariable")然后允许您在类的任何实例方法中以@instnc_var的形式访问该变量。我想知道为什么在@instnc_var之前需要一个冒号:。冒号有什么作用? 最佳答案 我的第一直觉是告诉你不要使用instance_variable_set除非你真的知道你用它做什么。它本质上是一种元编程工具或绕过实例变量可见性的黑客攻击

随机推荐