How can I remove blank lines from a block of text with regex?
Quick answer
For LF or CRLF text, match a line containing only spaces or tabs and its line ending. In Python, use re.sub(r'(?m)^[ \t]*\r?\n', '', text); in JavaScript, use text.replace(/^[ \t]*\r?\n/gm, ''). The multiline setting lets ^ match each line, and the global replacement removes repeated matches. A final blank line without a line ending needs separate handling.
The question, the details, the next step.
A practical checklist
Confirm whether the input uses LF or CRLF line endings.
Decide whether “blank” means empty or spaces-and-tabs-only.
Use Python
(?m)or JavaScript’smflag for line-start matching.Use JavaScript’s
gflag to remove every matching line.Check separately for a final whitespace-only line without a newline.
Test a small sample and verify that nonblank lines and intended trailing newlines remain.
A few more useful answers
Why is the `m` flag needed in JavaScript?
Without multiline mode, ^ matches the start of the whole input, rather than each line. The m flag makes it match line boundaries; g is separate and applies replacements to repeated matches. [S2]
Will this remove lines containing nonbreaking spaces?
Not with [ \t]*: that character class matches ordinary spaces and tabs only. The supplied references do not establish a pattern for all Unicode whitespace, so identify the characters in your input and choose a suitable approach.
Sources
References used for this guide.
- [S1] Python 3 regular-expression operations: multiline anchors and substitution docs.python.org · Checked
- [S2] MDN: JavaScript regular-expression flags and multiline behavior developer.mozilla.org · Checked
