Regular expressions can easily and quickly remove trailing spaces from every line in your query window as well as a few other tasks I’ll explain. To get started, you need to know how to specify the end of a line. There are two ways to specify the end of a line. You can use the “ \n” escape sequence or the end of line metacharacter “$”. Figure 1 shows how to remove a single trailing space from however many lines end that way. A more robust regular expression is shown in Figure 2. And a reader offers a keyboard shortcut to do the same thing without using regular expressions – see the comments section at the bottom. Removing extra blank lines is also described at the end of the post.
Figure 1. Replace space newline “ \n” with newline “\n” to remove one trailing space.
The problem with the syntax shown in Figure 1 is that you’ll have to iteratively click Replace All multiple times if you have more than one trailing space on some lines.
There is an easy fix that will remove all trailing spaces from all lines with a single Replace All. Add a “+” sign after the space and before the “\n” escape sequence. In other words, you want to use “ +\n” as your search string.
Figure 2. Replace space plus newline “ +\n” with newline “\n” to remove all trailing spaces.
Alternatively, you can use the end of line metacharacter expression “ +$” as your search string and have no replacement string.
Figure 3. Replace space plus dollar “ +$” with nothing to remove all trailing spaces.
Notice that I used “ and ” to delimit my find and replace strings. As the screen captures show, there aren’t any quotes around the find and replace strings.
Once you understand the pattern of using the “+” metacharacter, you can extend it to other edits such as normalizing inline comments to be exactly two consecutive dashes. Sometime you will see inline comments with more than two consecutive dashes. Use “--+” as your search string and “--” as your replacement string. Don’t use “-+” as your search string because it would change a single dash to two consecutive dashes. That’s why you should use use “--+” to find all occurrences of two or more dashes.
Figure 4. Replace dash dash plus “--+” with dash dash “--” to normalize inline comments at two dashes.
Once you understand the “\n” escape sequence for the end of a line, you can use this knowledge to remove superfluous blank lines. Sometimes when copy and pasting from a web page or email, you end up with a blank line inserted after each line in the source. This is easy to fix using regular expressions. When a blank line follows a line of text, you have two consecutive newline characters. Use “\n\n” as your search string and “\n” as your replacement string to remove the superfluous blank lines as shown in Figure 5.
Figure 4. Regular expression to remove superfluous lines when every other line is blank.