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.
Code
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
Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.WCAG Color Contrast CheckerCalculate WCAG 2.1 color contrast ratios between foreground and background colors. Verify AA and AAA compliance levels for normal and large text accessibility.CSS Color Name LookupTranslate between CSS keyword color names and hex values with RGB and HSL conversions, exact name matching, and nearest-color suggestions.Tailwind Color Palette GeneratorGenerate a balanced 50-950 Tailwind CSS custom property color scale from any hex, RGB, or HSL base color with WCAG 2.1 contrast ratios for every stop.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.