你知道在 Ruby 字符串中选择 ANSI 转义码(转义序列)的正则表达式吗?我说的是这个:
http://ascii-table.com/ansi-escape-sequences.php
我正在寻找经过良好测试和可靠的东西。
你知道在 Ruby 字符串中选择 ANSI 转义码(转义序列)的正则表达式吗?我说的是这个:
http://ascii-table.com/ansi-escape-sequences.php
我正在寻找经过良好测试和可靠的东西。
我有基于其他代码的代码。很久以前的事了,我忘记了出处,但可能是这个。以下是我用来将彩色 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>"
修改它以满足您的需求。