CSS Minify & Beautify — Java source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// css-minify — CSS minifier & beautifier. Java port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as \u0000n\u0000 sentinels and drops /* */ comments; every
// textual rule then runs on the masked text with java.util.regex patterns
// carrying no lookaround (backreferences are supported) so the Go twin
// reproduces byte-identical output. minify — collapse whitespace, strip
// spaces around {} ; : , > (sibling + and ~ combinators keep theirs), drop
// the last semicolon before }, lowercase hexes, shorten #aabbcc → #abc
// (never 8-digit alpha), strip leading zeros (0.5 → .5) and trailing
// fraction zeros (1.50 → 1.5, 1.00 → 1, .00 → 0). beautify — one selector
// per block, one declaration per line at 2-space depth, each declaration
// keeping its own semicolon. Errors travel in FormatResult.error (null
// mirrors TS null); empty input is a successful empty output, never an
// error.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Package-private: display snippets keep the repo filename (css-minify.java),
// which need not match the class name.
final class CssMinify {
/** TS CssFormatResult: error is null exactly on success. */
static final class FormatResult {
final String output;
final String error;
FormatResult(String output, String error) { this.output = output; this.error = error; }
}
/** mask() outcome: error != null on failure. */
private static final class Masked {
String masked = "";
final List<String> strings = new ArrayList<>();
String error;
}
private static final Pattern WS = Pattern.compile("\\s+");
private static final Pattern STRUCT = Pattern.compile("\\s*([{};:,>])\\s*");
private static final Pattern TRAILING_SEMIS = Pattern.compile(";+}");
private static final Pattern HEX_LOWER = Pattern.compile("#[0-9a-fA-F]{3,8}");
private static final Pattern HEX_PAIR = Pattern.compile("#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3([^0-9a-f]|$)");
private static final Pattern LEADING_ZERO = Pattern.compile("(^|[^A-Za-z0-9_.#$%-])0+(\\.[0-9]+)");
private static final Pattern FRACTION_ZEROS = Pattern.compile("(\\.[0-9]*[1-9])0+([^0-9]|$)");
private static final Pattern INTEGRAL_ZEROS = Pattern.compile("(^|[^A-Za-z0-9_.#$%-])([0-9]+)\\.0+([^0-9]|$)");
private static final Pattern DOT_ZEROS = Pattern.compile("(^|[^A-Za-z0-9_.#$%-])\\.0+([^0-9]|$)");
private static final Pattern SENTINEL = Pattern.compile("\u0000([0-9]+)\u0000");
/** Scan CSS into a masked text where every string literal is replaced by
* a \u0000n\u0000 sentinel (n = index into Masked.strings). Comments are
* dropped; a backslash escapes the next character inside a literal. */
private static Masked mask(String raw) {
Masked m = new Masked();
StringBuilder out = new StringBuilder();
int i = 0;
while (i < raw.length()) {
char ch = raw.charAt(i);
if (ch == '"' || ch == '\'') {
int start = i;
i++;
while (i < raw.length() && raw.charAt(i) != ch) {
if (raw.charAt(i) == '\\' && i + 1 < raw.length()) i++; // escaped char
i++;
}
if (i >= raw.length()) { m.error = "Unterminated string"; return m; }
i++;
m.strings.add(raw.substring(start, i));
out.append('\u0000').append(m.strings.size() - 1).append('\u0000');
} else if (ch == '/' && i + 1 < raw.length() && raw.charAt(i + 1) == '*') {
int end = raw.indexOf("*/", i + 2);
if (end < 0) { m.error = "Unterminated comment"; return m; }
i = end + 2;
} else {
out.append(ch);
i++;
}
}
m.masked = out.toString();
return m;
}
/** Substitute the sentinels back with the original string literals. */
private static String unmask(String text, List<String> strings) {
return SENTINEL.matcher(text).replaceAll(m -> strings.get(Integer.parseInt(m.group(1))));
}
/** Conservative minification — see the header for the exact rule list. */
static FormatResult minifyCss(String raw) {
String text = raw.strip();
if (text.isEmpty()) return new FormatResult("", null); // empty input is NOT an error
Masked m = mask(text);
if (m.error != null) return new FormatResult("", m.error);
String css = WS.matcher(m.masked).replaceAll(" ");
css = STRUCT.matcher(css).replaceAll("$1");
css = TRAILING_SEMIS.matcher(css).replaceAll("}");
css = css.strip();
css = HEX_LOWER.matcher(css).replaceAll(match -> match.group().toLowerCase());
// '$10$2' in the TS: only two groups exist, so Java reads $1 + "0" + $2;
// the callback form says exactly that.
css = HEX_PAIR.matcher(css).replaceAll(match -> "#" + match.group(1) + match.group(2) + match.group(3) + match.group(4));
css = LEADING_ZERO.matcher(css).replaceAll("$1$2");
css = FRACTION_ZEROS.matcher(css).replaceAll("$1$2");
css = INTEGRAL_ZEROS.matcher(css).replaceAll("$1$2$3");
css = DOT_ZEROS.matcher(css).replaceAll(match -> match.group(1) + "0" + match.group(2));
return new FormatResult(unmask(css, m.strings), null);
}
/** Structural beautifier — 2-space indentation, declarations one per line. */
static FormatResult beautifyCss(String raw) {
String text = raw.strip();
if (text.isEmpty()) return new FormatResult("", null);
Masked m = mask(text);
if (m.error != null) return new FormatResult("", m.error);
String css = WS.matcher(m.masked).replaceAll(" ");
StringBuilder out = new StringBuilder();
StringBuilder buffer = new StringBuilder();
int[] depth = {0};
class Flusher {
void flush(boolean semi) {
String decl = WS.matcher(buffer).replaceAll(" ").strip();
if (!decl.isEmpty()) {
out.append(" ".repeat(depth[0])).append(decl);
if (semi) out.append(';');
out.append('\n');
}
buffer.setLength(0);
}
String takeSelector() {
String sel = WS.matcher(buffer).replaceAll(" ").strip();
buffer.setLength(0);
return sel;
}
}
Flusher f = new Flusher();
for (int i = 0; i < css.length(); i++) {
char ch = css.charAt(i);
if (ch == '{') {
String sel = f.takeSelector();
if (sel.isEmpty()) return new FormatResult("", "Block without a selector");
out.append(" ".repeat(depth[0])).append(sel).append(" {\n");
depth[0]++;
} else if (ch == '}') {
f.flush(false);
depth[0]--;
if (depth[0] < 0) return new FormatResult("", "Unbalanced }");
out.append(" ".repeat(depth[0])).append("}\n");
} else if (ch == ';') {
f.flush(true);
} else {
buffer.append(ch);
}
}
if (depth[0] != 0) return new FormatResult("", "Unclosed block");
f.flush(false);
return new FormatResult(unmask(out.toString(), m.strings), null);
}
/** Demo: minify then beautify the same sheet. */
public static void main(String[] args) {
String sheet = "@media (max-width: 600px) { /* comment */ body { color : #AABBCC; margin : 0.50px; content : \"a, b\" ; }}";
System.out.println(minifyCss(sheet).output); // @media (max-width: 600px){body{color:#abc;margin:.5px;content:"a, b"}}
System.out.print(beautifyCss(sheet).output);
System.out.println(minifyCss("a{b:c;d}").error == null ? "ok" : "err");
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →