删除 ASCII 颜色代码 [英] Remove ASCII color codes
问题描述
所以,我遇到了一个问题.我正在从 Logger 中捕获一些内容,输出如下所示:
So, I'm having an issue. I'm catching some stuff from a Logger, And the output looks something like this:
11:41:19 [INFO] ←[35;1m[Server] hi←[m
我需要知道如何删除那些讨厌的 ASCII 颜色代码(或解析它们).
I need to know how to remove those pesky ASCII color codes (or to parse them).
推荐答案
如果它们完好无损,它们应该由 ESC (U+001B
) plus [
plus 组成以分号分隔的数字列表,加上 m
.(请参阅 https://stackoverflow.com/a/9943250/978917.)在这种情况下,您可以通过写作:
If they're intact, they should consist of ESC (U+001B
) plus [
plus a semicolon-separated list of numbers, plus m
. (See https://stackoverflow.com/a/9943250/978917.) In that case, you can remove them by writing:
final String msgWithoutColorCodes =
msgWithColorCodes.replaceAll("u001B\[[;\d]*m", "");
...或者您可以在检查日志时使用 less -r
来利用它们.:-)
. . . or you can take advantage of them by using less -r
when examining your logs. :-)
(注意:这是特定于颜色代码的.如果您还发现其他 ANSI 转义序列,您需要对其进行概括.我认为一个相当通用的正则表达式应该是 u001B\[[;;\d]*[ -/]*[@-~]
.你可以找到 http://en.wikipedia.org/wiki/ANSI_escape_code 很有帮助.)
(Note: this is specific to color codes. If you also find other ANSI escape sequences, you'll want to generalize that a bit. I think a fairly general regex would be u001B\[[;\d]*[ -/]*[@-~]
. You may find http://en.wikipedia.org/wiki/ANSI_escape_code to be helpful.)
如果序列不完整—也就是说,如果它们以某种方式被破坏了—那么你就必须调查并弄清楚到底发生了什么损坏.
If the sequences are not intact — that is, if they've been mangled in some way — then you'll have to investigate and figure out exactly what mangling has happened.
这篇关于删除 ASCII 颜色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!