DevKits

Text

Remove empty lines

Flags: gm

Strip blank lines (lines containing only whitespace) from a block of text.

Pattern

Regular expression

^\s*$\r?\n

How it works

The `m` flag makes `^` and `$` match line boundaries. `\s*` allows the line to contain any whitespace, and `\r?\n` consumes the trailing newline (both LF and CRLF).

Matches

  • `\n\n` (double newline)
  • ` \n` (whitespace-only line)

Non-matches

  • `text\n` (has content)

Language snippets

JavaScript

text.replace(/^\s*$\r?\n/gm, "");

Python

re.sub(r"^\s*$\r?\n", "", text, flags=re.M)

Go

re := regexp.MustCompile(`(?m)^\s*$\r?\n`)
re.ReplaceAllString(text, "")

Java

text.replaceAll("(?m)^\\s*$\\r?\\n", "")

Related patterns

Try any pattern live in the Regex Tester