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.
Code
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
Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.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.Regular Expression TesterTest regular expressions against sample text with live match highlighting, capture group extraction, and flags support for global, case-insensitive, and multiline modes.
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 :`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.