Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How do I combine something like query-replace with a regular expression search-and-replace that in part reuses the search result?

In my case, how to transform

The programmers are "sort of" confident that the subroutines "load_students" and "compute_student_grade" are without bugs.


The programmers are "sort of" confident that the subroutines \texttt{load_students} and \texttt{compute_student_grade} are without bugs.

I could use two query-replace and then hammer yes and no, but it seems sluggish for a big document. Also, I thought about including the whitespace in the searches (one  " and one , but that would not work in cases such as ... that's not the way to use "load_students", rather ...

Is there built-in stuff for this or do you write Elisp code?

share|improve this question
up vote 5 down vote accepted

You can use query-replace-regexp thus:

M-x query-replace-regexp RET
\"\([^[:space:]]+\)\" RET
\\texttt{\1} RET

The query string can be read as: match a sequence of one or more non-space characters into match group 1 (the parentheses are for grouping), all this enclosed by quotes.

The \1 on the replacement string inserts the match grouping.

The double backslash before texttt is for escaping the backslash character from interpretation.

If, instead, what you want to match is only multi-word symbols with underscores, then you need to change the match string to something like \(\w+_\w+\)

share|improve this answer
Wow! Just out of curiosity, why was it necessary to exclude the space characters? – Emanuel Berg May 29 '12 at 22:41
Don't know; I was just trying to interpret what you were trying to match and what not. Take it as an example only. – Juancho May 29 '12 at 23:22

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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