Page 1 of 1

How to quote or bracket selected text using regular expressions

Posted: Mon Jul 29, 2024 6:11 pm
by bbadmin
Suppose you want to selectively quote part of this text:
The words in the sentence the quick brown fox jumps over the lazy dog contain all the letters of the alphabet.
Start by selecting the appropriate part:
The words in the sentence the quick brown fox jumps over the lazy dog contain all the letters of the alphabet.
Then, set up the Replace command like this and click Replace All:

quote.png
quote.png (31.72 KiB) Viewed 17059 times

This will be the result:
The words in the sentence "the quick brown fox jumps over the lazy dog" contain all the letters of the alphabet.
By default the regular expression ".+", which matches one or more of any character, does not match end of line characters. So, if the selected text spans multiple lines, this will not work as expected. The solution is to override that default with the modifier "(?s)", like this:

quote2.png
quote2.png (32.31 KiB) Viewed 17059 times

If instead you want to bracket selected text, note that the brackets have to be escaped, so change the replacement expression to \($0\).

Obviously, this can be recorded as a macro, if it's something you do often.