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?


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+\)

  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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