To remove leading and training white spaces with regular expressions we have two options.
- Remove only the horizontal whitespace characters: spaces and tabs
- All whitespaces, including all vertical line breaking characters, in this case the empty lines are removed from the text as well.
To remove only the horizontal spaces, we use the \h
token that represents the space and tab characters. To remove all whitespaces we make use of the \s regex token which symbolizes all of the horizontal and vertical line breaking characters: [\r\n\t\f\v ]
The two expressions we work with are:
# If only spaces and tabs need to be removed ^\h*(.*?)\h*$ # If all whitespaces (line breaks too) ^\s*(.*?)\s*$
Removing whitespaces with Notepad++
Open the text file with leading and/or trailing whitespaces, then press [Ctrl+H] or use the Search/Replace... button in the top menu bar to bring up the Replace dialog.
There put the expression to the 'Find what:' field, and \1
to the 'Replace with:' text box.
Make sure the search mode is set to 'Regular expression'.
The 'Wrap around' checkbox is selected by default, ensuring that the whole document is being searched, not only the lines after the current cursor position.
Hit Replace All
Removing whitespaces with Vim
The Visual IMproved editor only recognizes spaces and tabs as whitespaces (\s). If you want to remove empty lines with Vim, please check my other guide here.
:%s:^\s*\(.\{-}\)\s*$:\1:
Comments