I think the best way to explain what I'm trying to do is using an example. Suppose one would want to replace all underlined words with italic ones in org-mode using a regular expression:

_example_ --> /example/

Using Perl regex, one could easily accomplish such a task with the grouping variables $1, $2, etc... using the expression s/_([^_]+)_/\/$1\//g for this case.

Are there similar "grouping variables" in Emacs? If not, then what is the most efficient way to perform such a replacement operation?

  • 1
    You really should ask Emacs first. Check the Elisp manual for the Emacs Lisp regexp syntax. You won't get far with regexps without some knowledge of this syntax. The manual is included with Emacs - you just need to hit C-h i. Help yourself.
    – Drew
    Dec 8, 2014 at 14:52
  • @Drew Thanks. I checked the manual, but didn't know it was under "eLisp > ... > Regxp Backslash". Found it now, only after I knew what to look for
    – Tymric
    Dec 8, 2014 at 15:01
  • 1
    i is your friend in a manual (but yes, you need to guess which manual).
    – Drew
    Dec 8, 2014 at 17:24

1 Answer 1


Use \(...\)for grouping and \1 to reference the first saved group (\2 for the second, all the way up to \9). E.g.:

query-replace-regexp: _\([^_]+\)_ into /\1/.

See Regexp Backslash in the Emacs Lisp Manual for more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.