ANSI SGR Color Escape Sequences

Emit ANSI SGR escape sequences to color terminal output, then strip every sequence with a regex so piped or CI output stays clean.

JavaCli Tooling

Code

snippet
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"));
    }
}

How it works

The code’s whole job belongs to the class TerminalColors and the functions colorize and main.

Watch out for

  • Every symbol it uses is a language built-in — nothing needs fetching.

Using it

Signature: static String colorize(String text, String sgr)

Output lines are prefixed (strips clean:), making what each step changes easy to notice.

Launch the file; main takes over and steps through colorize.

The key statements, annotated

return sgr + text + RESET;

Interactive Tools for This Topic

FAQ

What does ANSI SGR Color Escape Sequences print when run?
Invoke the file as-is — the `strips clean:` prefixes identify which step printed each line.