How to replace "(" with "\ (" in regexp, Emacs / elisp?

Question as a headline.

In particular, I'm pretty tired of having to type \(, etc. every time I need a bracket in an Emacs (interactive) regular expression (not to mention \\(in the code). So I wrote something like

(defadvice query-replace-regexp (before my-query-replace-regexp activate)
   (ad-set-arg 0 (replace-regexp-in-string "(" "\\\\(" (ad-get-arg 0)))
   (ad-set-arg 0 (replace-regexp-in-string ")" "\\\\)" (ad-get-arg 0)))))

in the hope that I can easily forget about emacs idiosyncrasy in regexp during the "interaction mode". Also, I cannot get the regular expression correctly ...

(replace-regexp-in-string "(" "\\\\(" "(abc")

gives \\(abcinstead of the desired \(abc. Other variations on the number of slashes just give errors. Thoughts?

Since I started the survey, I might also ask another question: since lisp code should not use interactive functions, we query-replace-regexpshould be fine, am I right?

+2
1

.

:

hi there mom
hi son!

-replace-regexp :

M-x query-replace-regexp (hi).*(mom) RET \1 \2! RET

hi mom!
hi son!

, . , ...

, replace-regexp-in-string \\(abc, - , \(abc. \ , , . "\t" - . , , "\\" - , .

, lisp , . find-file - . , interactive-p, :

(defadvice query-replace-regexp (before my-query-replace-regexp activate)
  (when (interactive-p)
    (ad-set-arg 0 (replace-regexp-in-string "(" "\\\\(" (ad-get-arg 0)))
    (ad-set-arg 0 (replace-regexp-in-string ")" "\\\\)" (ad-get-arg 0)))))
+7

Source: https://habr.com/ru/post/1760127/


All Articles