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", "")

Frequently asked questions

What is the regex for Remove empty lines?

The pattern ^\s*$\r?\n (flags: gm) matches Remove empty lines. 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).

What does this Remove empty lines pattern match?

It matches strings like `\n\n` (double newline), ` \n` (whitespace-only line), but rejects `text\n` (has content).

How do I use this pattern in JavaScript, Python, Go, Java?

Ready-to-run snippets are provided for JavaScript, Python, Go, Java. Copy the one for your language from the Language snippets section — each wraps the same core pattern in that language's regex API.

Related patterns

Try this pattern in a tool

Try any pattern live in the Regex Tester