您是否知道在Ruby字符串中选择ANSI转义码(转义序列)的正则表达式?我在说这个:
http://ascii-table.com/ansi-escape-sequences.php
我正在寻找经过良好测试和可靠的测试。
答案 0 :(得分:5)
我的代码基于其他一些代码。很久以前,我忘记了消息来源,但可能是this。以下是我用于将彩色ANSI文本转换为标记HTML格式的代码:
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
它与定义映射规则的哈希一起使用:
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
我这样用:
"red \x1b[31mapple\x1b[0m".ansi2html
# => "red <span class=\"red\">apple</span>"
修改它以满足您的需求。