Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs: regular expression replacing to change case

Every once in a while I want to replace all instances of values like:

<BarFoo> 

with

<barfoo> 

i.e. do a regular expression replace of all things inside angle brackets with its lowercase equivalent.

Anyone got a nice snippet of Lisp that does this? It's safe to assume that we're dealing with just ASCII values. Bonus points for anything that is generic enough to take a full regular expression, and doesn't just handle the angle brackets example. Even more bonus points to an answer which just uses M-x query-replace-regexp.

Thanks,

Dom

like image 792
Dominic Rodger Avatar asked Mar 24 '09 11:03

Dominic Rodger


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How do I replace in Emacs?

Simple Search and Replace Operations When you want to replace every instance of a given string, you can use a simple command that tells Emacs to do just that. Type ESC x replace-string RETURN, then type the search string and press RETURN. Now type the replacement string and press RETURN again.


Video Answer


1 Answers

Try M-x query-replace-regexp with "<\([^>]+\)>" as the search string and "<\,(downcase \1)>" as the replacement.

This should work for Emacs 22 and later, see this Steve Yegge blog post for more details on how Lisp expressions can be used in the replacement string.

For earlier versions of Emacs you could try something like this:

(defun tags-to-lower-case ()   (interactive)   (save-excursion     (goto-char (point-min))     (while (re-search-forward "<[^>]+>" nil t)       (replace-match (downcase (match-string 0)) t)))) 
like image 118
Luke Girvin Avatar answered Oct 02 '22 22:10

Luke Girvin