Susam Pal has a nice reminder on using query-replace-regexp. Most Emacs users know about the command and its binding Ctrl+Meta+% but Pal’s post mentions some less known features that can be very useful.
The first—and simplest—is using \&
in the replacement string. It expands to whatever was matched by the regular expression and is often useful.
The second feature is that you can call a function to compute the replacement string. You indicate such a function by beginning the replacement string with \,
followed by the appropriate s-expr. The example that Pal gives is \,(upcase \&)
which upper cases whatever the regular expression matched.
The final item involves matched substrings. Most Emacs users are familiar with the idea of matched substrings and the corresponding \n
notation in the replacement string that expands to the nth matched substring. Sometimes, though, it’s convenient to capture the nth substring as a number. To do that you simply use the notation \#n
. This is mostly useful when you are calculating the replacement string. For example, you could add 1 to the third matched substring with \,(+ 1 \#3)
. Pal has a couple of more robust examples in his post.
All this is, in a sense, old news but Pal’s post serves as a very useful reminder of some of the corner cases in query-replace-regexp
that can occasionally save the day. Pal has a real, but simple, example of its use in his post so head on over and read it.
Of course, all this applies to the other regexp search and replace functions as well so it’s definitely worth knowing.