Find trailing whitespace
Spot the invisible spaces and tabs clinging to line ends before they break diffs, fail linters, or bloat a file with silent whitespace.
Last updated
Matches
- Hello world Goodbye
- Tabs here: Next line
Doesn’t match
- Hello world Goodbye
- Clean line one Clean line two
Why it’s written this way
The character class [ \t] matches a literal space or a tab, and the trailing + requires one or more of either right before the line ends. Anchoring with $ pins the match to the end of a line rather than the end of the whole string.
The m flag is what makes $ mean 'end of each line' instead of 'end of the string' — drop it and this pattern would only ever check the very last line of a multi-line file.
Edge cases to know
- →It only catches ASCII space and tab — a non-breaking space (U+00A0) or other Unicode whitespace slips through untouched.
- →It flags a line's trailing run but says nothing about whitespace elsewhere on the line, such as double spaces mid-sentence.
Part by part
- [ \t]+
- One or more spaces or tabs. Listing both matters because a file edited by several people usually contains a mix, and a space-only pattern leaves the tabs behind.
- $
- End of line rather than end of string, because the m flag is set. That single flag is what turns this from a one-shot check into a whole-file sweep.
Common mistakes
\s+$The whitespace class includes the newline itself, so with the m flag this greedily eats blank lines and joins paragraphs together. It is the most common way a cleanup regex quietly mangles a file.
[ \t]+$[ \t]+$ without the m flagWithout m, the dollar anchors to the end of the entire string, so only the very last line is checked and every other trailing space survives the cleanup.
[ \t]+$ with flags gm[ \t]*$A star matches zero characters, so the pattern succeeds at the end of every line whether or not there is whitespace there. Used with a replace, it inserts nothing everywhere and reports a match count equal to the line count.
Questions
Why does trailing whitespace matter?
Mostly because of diffs. A stray space at the end of a line makes that line appear changed when nothing meaningful was edited, which adds noise to every review and can cause spurious merge conflicts.
Will it catch a line that is only spaces?
Yes, the whole line matches, since the run of spaces extends to the end of it. If you want to distinguish that case from a genuinely blank line, the blank-lines pattern in this collection is the one to use.
Does it handle Windows line endings?
Yes. The carriage return is not in the class and not matched, so on CRLF files the whitespace before it is found and the line ending is left alone — which is what you want.
Should my editor just do this?
Yes, and most will trim on save once you turn it on. This pattern is for the files that arrived from somewhere else, and for the one-off audit of a repository where the setting was never enabled.