← 中文资源

简体中文版本

ANSI SGR 彩色转义序列

用 ANSI SGR 转义序列给终端输出上色:SGR 常量拼接彩色文本,再用正则剥掉序列,重定向到管道或 CI 时输出保持干净可读。

阅读英文原文

实现说明

ANSI SGR 彩色转义序列可以归结为类 TerminalColors和函数 colorize、main。

使用要点

  • 跑完文件,输出里会留下标记——strips clean:。
  • 运行整个文件:main 会依次驱动 colorize。

常见问题

运行「ANSI SGR 彩色转义序列」会打印什么?

运行文件本身,strips clean: 这些前缀各对应一段演示逻辑。

入口签名:static String colorize(String text, String sgr)

核心语句

return sgr + text + RESET;

代码示例

public class TerminalColors {

    // ANSI SGR escape sequences: ESC [ <code> m color terminal output
    static final String RESET  = "\u001b[0m";
    static final String RED    = "\u001b[31m";
    static final String GREEN  = "\u001b[32m";
    static final String YELLOW = "\u001b[33m";
    static final String BOLD   = "\u001b[1m";

    static String colorize(String text, String sgr) {
        return sgr + text + RESET;
    }

    public static void main(String[] args) {
        System.out.println(colorize("build failed", RED));
        System.out.println(colorize("27 tests passed", GREEN));
        System.out.println(colorize("deprecated flag", YELLOW));
        System.out.println(colorize("summary", BOLD));

        // no terminal when redirected to a pipe or CI: strip every SGR sequence with a regex to keep output clean
        String decorated = colorize("warn", YELLOW) + ": slow query";
        String plain = decorated.replaceAll("\u001b\\[\\d*m", "");
        System.out.println(plain);
        System.out.println("strips clean: " + plain.equals("warn: slow query"));
    }
}