Replace double backslash with single backslash in Emacs

emacsregex

I have created a regular expression with re-builder in Emacs. I use C-c C-w to copy it to the kill-ring.

The kill-ring shows:

"\\(defun\\)"

First, I modified the copy function to get rid of the "".

\\(defun\\)

My other problem is, the regex in the kill-ring contains double backslashes, rendering it unusable for functions like query-replace-regexp, which I want to yank it back into from the kill-ring.

These functions expect single backslashes, like

\(defun\)

So I thought I could replace the '\\' with the '\' before copying it to the kill-ring by doing this:

(replace-regexp-in-string "\\\\" "\\" "\\(defun\\)" nil t)

When executing the function the minibuffer shows "\\(defun\\)" instead of "\(defun\)" as a result.

What am I doing wrong?

Best Answer

This works for me:

(defun my-reb-copy ()
  "Copy current RE into the kill ring without quotes and single
backslashes for later insertion."
  (interactive)
  (reb-update-regexp)
  (let* ((re (with-output-to-string
               (print (reb-target-binding reb-regexp))))
         (str (substring re 2 (- (length re) 2))))
    (with-temp-buffer
      (insert str)
      (goto-char (point-min))
      (while (search-forward "\\\\" nil t)
        (replace-match "\\" nil t))
      (kill-new (buffer-substring (point-min) (point-max))))
    (message "Regexp copied to kill-ring")))

(define-key reb-mode-map "\C-c\C-t" 'my-reb-copy)