Question

Do you know a regular expression for selecting ANSI escape codes (escape sequences) in a Ruby string? I'm talking about this:

http://ascii-table.com/ansi-escape-sequences.php

And I'm looking for something well tested and reliable.

Was it helpful?

Solution

I have code that was based on some other code. It was a long time ago, and I forgot the source, but it may be this. The following is the code that I use to convert a colored ANSI text into a tagged HTML format:

require "strscan"
class String
    def ansi2html
        ansi = StringScanner.new(self)
        html = StringIO.new
        until ansi.eos?
            if ansi.scan(/\e\[0?m/)
                html.print(%{</span>})
            elsif ansi.scan(/\e\[0?(\d+)m/)
                html.print(%{<span class="#{AnsiColor[ansi[1]]}">})
            else
                html.print(ansi.scan(/./m))
            end
        end
        html.string
    end
end

It is used together with a hash defining the mapping rule:

class String
    AnsiColor = {
        "1" => "bold",
        "4" => "underline",
        "30" => "black",
        "31" => "red",
        "32" => "green",
        "33" => "yellow",
        "34" => "blue",
        "35" => "magenta",
        "36" => "cyan",
        "37" => "white",
        "40" => "bg-black",
        "41" => "bg-red",
        "42" => "bg-green",
        "43" => "bg-yellow",
        "44" => "bg-blue",
        "45" => "bg-magenta",
        "46" => "bg-cyan",
        "47" => "bg-white",
    }
end

I use it like this:

"red \x1b[31mapple\x1b[0m".ansi2html
# => "red <span class=\"red\">apple</span>"

Modify it to meet your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top