Skip to content

Regex for Blank Lines — Pattern, Examples & Caveats

Pattern flags: gm
^\s*\n

This pattern matches lines that are empty or contain only whitespace, followed by a newline. With global and multiline flags it is used to remove blank lines from text while keeping content lines intact. Text patterns operate on prose and whitespace: finding repeated words, trimming trailing spaces, collapsing blank lines or restricting characters to a safe set. They are the workhorses of editors, linters and cleanup pipelines. Because natural text is messy, these patterns favor pragmatism and are usually applied with global/multiline flags across many lines at once. It uses the gm flag(s). Apply it to the whole input as a format contract. Because \s includes \n, the pattern can span multiple newlines; use ^[ \t]*\n to match strictly one blank line at a time. Removing all matches may join paragraphs; decide whether to collapse runs of blank lines to one instead. The final line without a trailing newline is not matched — handle end-of-text separately if needed. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • ^ — start of a line (multiline)
  • \s* — zero or more whitespace characters (the line may be empty or spaces only)
  • \n — the newline ending the blank line
  • g and m flags — match every blank line across the text

What it matches

What it does not match

text a content

When to use it

Reach for a text pattern when cleaning or analyzing prose: trimming trailing whitespace, collapsing blank lines, finding duplicated words or restricting characters to a safe set. Apply it with global and multiline flags across the whole document in one pass. Because natural language is irregular, treat matches as candidates for review rather than automatic edits, and test on representative samples so you do not mangle legitimate content such as intentional repetition or code blocks.

Caveats

  • Because \s includes \n, the pattern can span multiple newlines; use ^[ \t]*\n to match strictly one blank line at a time.
  • Removing all matches may join paragraphs; decide whether to collapse runs of blank lines to one instead.
  • The final line without a trailing newline is not matched — handle end-of-text separately if needed.

Code examples

JavaScript
const re = /^\s*\n/gm;
const input = "
";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^\s*\n", re.M)
value = "
"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^\\s*\\n", Pattern.MULTILINE);
Matcher m = p.matcher("
");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "
";
if (preg_match('/^\s*\n/m', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

How do I collapse multiple blank lines into one?

Match runs of blank lines with (^[ \t]*\n){2,} and replace with a single newline, preserving paragraph separation while removing excess gaps.

Why does \s* sometimes eat extra lines?

\s matches newlines too, so ^\s*\n can consume several line breaks. Restrict to [ \t]* if you want to remove exactly one blank line per match.

Why use multiline and global flags for text cleanup?

Multiline makes ^ and $ match at each line boundary, and global applies the pattern across the whole text. Together they let you trim or collapse every line in one pass instead of looping manually.

How do I match across newlines?

The dot does not match newline by default. Use the s (dotAll) flag, or the [\s\S] character class, to span lines — essential for block comments and multi-line constructs.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →