For example I want to make all text in parenthesis, (), UPCASE. It's trivial to do the following interactively:
M-x query-replace-regexp
replace: "(\(.+?\))"
with : "(\,(upcase \1))"
Instead I want to write a defun
which will do that:
(defun upcs ()
(interactive)
(goto-char 1)
(while (search-forward "(\\(.+?\\))" nil t) (replace-match "(\\,(upcase \\1))" t nil)))
but it doesn't work! While the following works (it appends foo
and bar
to the parenthesized texts):
(defun HOOK ()
(interactive)
(goto-char 1)
(while (search-forward-regexp "(\\(.+?\\))" nil t) (replace-match "(foo \\1 bar)" t nil)))
Luke's answer almost does the job but not quite. The original poster wanted all the text that was enclosed in parenthesis converted to upper case while Luke's code converts the code to upper case AND ALSO removes the parenthesis. A slight modification to the regex provides the correct solution:
(defun upcs ()
(interactive)
(goto-char 1)
(while (search-forward-regexp "\\([^\\)]+\\)" nil t)
(replace-match (upcase (match-string 1)) t nil)))
First of all, you're using search-forward
in your first function. This takes a string literal rather than a regular expression. You should be using search-forward-regexp
, as you do in your second function.
Secondly, while this code is valid as a replace value for query-replace-regexp
, I don't think you can pass it to replace-match
:
(\\,(upcase \\1))
You can get the value of the match found by search-forward-regexp
using the match-string
function.
Finally, I'm not sure your search regular expression is correct.
I think you need something along these lines:
(defun upcs ()
(interactive)
(goto-char 1)
(while (search-forward-regexp "(\\([^\\)]+\\))" nil t)
(replace-match (upcase (match-string 1)) t nil)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With