Course contentsShow
← Java
Lesson 2291 of 2,87044. Regular ExpressionsFree lesson

Whitespace Normalization Patterns

Use patterns to match and replace multiple spaces, tabs, newlines for text normalization and cleaning.

Whitespace Normalization Patterns

What you'll learn: How to use regular expressions to clean up messy whitespace by matching and replacing multiple spaces, tabs, and newlines in text.

The Core Idea

Real-world text data is often messy—users paste content with inconsistent spacing, extra tabs, multiple blank lines, or mixed whitespace characters. Whitespace normalization patterns use regex to detect these variations and replace them with clean, consistent spacing. Think of it like a smart text vacuum that sucks up all the scattered whitespace clutter and replaces it with neat, uniform spacing.

Common Normalization Patterns

Collapsing multiple spaces into one:

String messy = "Hello    world   from    Java";
String clean = messy.replaceAll("\\s+", " ");
// Result: "Hello world from Java"

The \\s+ pattern matches one or more whitespace characters (spaces, tabs, newlines) and replaces them with a single space.

Removing leading/trailing whitespace from each line:

String text = "  Line 1  \n   Line 2  \n  Line 3  ";
String cleaned = text.replaceAll("(?m)^\\s+|\\s+$", "");
// Removes spaces at start/end of each line

Normalizing line breaks:

String mixed = "Line1\r\nLine2\rLine3\nLine4";
String normalized = mixed.replaceAll("\\r\\n?", "\n");
// Converts all line endings to \n

Collapsing blank lines:

String multipleBlankLines = "Para 1\n\n\n\nPara 2";
String singleBlank = multipleBlankLines.replaceAll("\n{3,}", "\n\n");
// Reduces 3+ newlines to just 2

Practical Applications

These patterns are essential for cleaning user input, parsing scraped web content, normalizing log files, and preparing text for storage or display. They transform chaotic formatting into predictable, processable data.

Key Takeaway: Whitespace normalization patterns use replaceAll() with regex like \\s+ to collapse multiple whitespace characters into consistent formatting, making messy text clean and uniform.