How to quote or bracket selected text using regular expressions

Instructional HowTos, posted by users. No questions here please.

Moderators: AmigoJack, bbadmin, helios, Bob Hansen, MudGuard

Post Reply
User avatar
bbadmin
Site Admin
Posts: 903
Joined: Mon Feb 17, 2003 8:54 pm
Contact:

How to quote or bracket selected text using regular expressions

Post 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 7620 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 7620 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.
Post Reply