Regex to Match Blank or Empty Lines
Match blank or empty lines in multi-line text, including lines containing only whitespace. Useful for removing excess blank lines from code or text. Free regex tester.
Regular Expression
/^\s*$/gm
Token Breakdown
| Token | Description |
|---|---|
| ^ | Anchors at the start of the string (or line in multiline mode) |
| \s | Matches any whitespace character (space, tab, newline) |
| * | Matches the preceding element zero or more times (greedy) |
| $ | Anchors at the end of the string (or line in multiline mode) |
Detailed Explanation
This regex matches blank lines in multi-line text, including lines that are completely empty and lines containing only whitespace characters. Here is the token-by-token breakdown:
^ — Anchors the match at the start of a line. With the m (multiline) flag, this matches at the beginning of each line in the text, not just the beginning of the entire string.
\s* — Matches zero or more whitespace characters. This handles both truly empty lines (zero characters between the start and end anchors) and lines containing only spaces, tabs, or other whitespace characters. The asterisk quantifier allows zero occurrences so empty lines with no characters at all are matched.
$ — Anchors the match at the end of a line. With the multiline flag, this matches at the end of each line.
The g flag enables global matching to find all blank lines in the text, and the m flag enables multiline mode so the ^ and $ anchors work on a per-line basis rather than matching only the start and end of the entire string.
Blank line detection is useful in many text processing scenarios: removing excessive blank lines from code or documents, counting paragraph breaks, detecting section separators, cleaning up pasted text, and enforcing code style rules about maximum consecutive blank lines. Many linters have rules limiting consecutive blank lines (for example, ESLint's no-multiple-empty-lines rule).
This pattern is commonly used in text editors for search and replace operations, build tools for code formatting, and content processing pipelines. To remove blank lines, replace matches with an empty string.
Example Test Strings
| Input | Expected |
|---|---|
| Match | |
| Match | |
| Match | |
| not blank | No Match |
| a | No Match |
Try It — Interactive Tester
Match Highlighting(1 match)
Matches & Capture Groups
5 charsFlags: gmMatches: 1Ctrl+Shift+C to copy regex