I have a buffer with a lot of instances of words surrounded by '<' and '>', and I want to replace them all with the just capitalized word. E.g. <foo> -> FOO.

I read the regex chapter of the gnu emacs manual, but I'm still lost.


This will replace next occurrence after point:

  (re-search-forward "<\\(.+?\\)>")
  (upcase-region (match-beginning 1) (match-end 1)))

re-search-forward searches for the next match of <foo>. You can find a fairly detailed explanation on Emacs Wiki on Regexp.

After Emacs matches the next occurrence of regexp, calling match-beginning and match-end will return the position of the beginning and the end of the match.

The number 1 in the argument means the first group of the match, that is the part of regexp in the first (and in this case, the only) pair of parenthesis.

Finally upcase-region will upcase the text in the range marked by match-beginning and match-end.

Code above only replaces the next occurrence. Since re-search-forward returns nil when failed and t when succeed, we can ask Emacs to keep going until no further match is found:

(while (re-search-forward "<\\(.+?\\)>" nil t)
  (upcase-region (match-beginning 1) (match-end 1)))
  • Thank you, that's very helpful! However, it's replacing <foo> with <FOO> and not FOO without the delimiters. But I just did want I wanted with M-x query-replace-regexp <RET> <\(.+?\)> <RET> \,(upcase \1) <RET>
    – NTC
    Oct 21 '18 at 18:28
  • Try this variant: (while (re-search-forward "<\\(.+?\\)>" nil t) (replace-match (upcase (match-string 1))))
    – amitp
    Oct 21 '18 at 22:40
  • Oh sorry! I didn't read the question as carefully as I should. Since you have the answer and mine isn't valid, how about you move your answer to the question's comment and I remove my answer?
    – Yuan Fu
    Oct 21 '18 at 22:43

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.