Strip ANSI Escape Sequences

Strip ANSI escape sequences from colored CLI output with one regex covering CSI, OSC, and two-byte controls, leaving plain text untouched.

JavaCli Tooling

Code

snippet
import java.util.regex.Pattern;

public class LogCleaner {

    // ANSI escape sequences 分三类:CSI 控制串、OSC 段、双字符转义
    private static final Pattern ANSI = Pattern.compile(
            "\u001B\\[[0-9;]*[A-Za-z]"                     // CSI:颜色与光标控制
            + "|\u001B\\][^\u0007]*(?:\u0007|\u001B\\\\)"  // OSC:窗口标题等
            + "|\u001B[@-_]");                             // ESC + 单个控制字符

    static String strip(String colored) {
        return ANSI.matcher(colored).replaceAll("");
    }

    public static void main(String[] args) {
        String colored = "\u001B[32mOK\u001B[0m"
                + " \u001B[1;31mfailed\u001B[0m"
                + " plain\u001B]0;title\u0007";
        System.out.println("raw      : [" + colored + "]");
        System.out.println("stripped : [" + strip(colored) + "]");
        System.out.println("clean ok : " + strip(colored).equals("OK failed plain"));
        System.out.println("untouched: " + strip("no colors here").equals("no colors here"));
    }
}

How it works

The moving parts are the class LogCleaner and the functions strip and main.

What to watch for

  • Nothing more than the toolchain is needed, and no dependency resolution takes place.

Using it

Signature: static String strip(String colored)

The run emits 4 labeled sections — raw : [, stripped : [, clean ok :, untouched: — one per step.

main is the driver: it invokes strip before returning.

Key statements

return ANSI.matcher(colored).replaceAll("");

Interactive Tools for This Topic

FAQ

What does Strip ANSI Escape Sequences print when run?
Running the file directly is enough — expect labeled output lines such as `raw : [`, `stripped : [`, `clean ok :`.