Regular Expression Search/Replace in Emacs

I'm a big fan of regular expressions - there's no better way to tweak many multiple instances of an HTML tag or attribute, or change a variable name across a bunch of PHP scripts.

Perl sets the standard, but Emacs also provides regex support quite nicely - the only thing is keeping the subtle differences straight. I'm committing this to the site so that I don't have to keep searching hundreds of Emacs mailing list archives the next time I forget.

When specifying a group or character class in an Emacs, you have to escape the container characters. Take the following Perl regex:

/foo (.*?) bar/

This will match any string that has the words 'foo' and 'bar' and extract the string between them. This is how to format it in Emacs:

foo \(.*?\) bar

If you want to use a backrefence in a regex find/replace, use the format

\n

where n is the matched group you want to substitute. So say you have a buffer containing

foo bat bar

and you did a search for

foo \(.*?\) bar

and replaced it with

foo bar \1

The contents of the buffer will now read

foo bar bat.

Read the Emacs manual page on regexps for more details.

Also

Syndicate content

Twitter

  • @eaton I predict the following words will be overused: Downfall, Socialism, Scared. 5 years 33 weeks ago
  • I refuse to pay $15 for razor cartridges any more. Finally ordered a double-edged safety razor with blades for only about $9 more. 5 years 33 weeks ago
  • Aww, it's OK, Sabres. 5 years 33 weeks ago
  • @bobpatin The opt key doesn't disable the confirmation, it allows you to delete files in a playlist (not just remove them from that list) 5 years 33 weeks ago
  • @mrbill congrats! (on the degree & the tattoo - you've seen the Masonic Ink site no doubt?) 5 years 33 weeks ago

Older

Contact

Andy Chase
(978) 297-6402
andychase [at] gmail.com
GPG/PGP Public Key