如何在正则表达式中替换"("和"\(",Emacs/elisp风味?

pol*_*lot 2 emacs elisp

问题为标题.

更具体地说,\(每次我想在Emacs(交互式)regexp函数中使用括号(更不用说\\(代码中)时,我都厌倦了必须输入等等.所以我写了类似的东西

(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)))))
Run Code Online (Sandbox Code Playgroud)

希望在"交互模式"期间我可以方便地忘记emage在regexp中的特性.除了我不能正确的regexp ...

(replace-regexp-in-string "(" "\\\\(" "(abc")
Run Code Online (Sandbox Code Playgroud)

给出\\(abc的,而不是想要的\(abc.斜杠数量的其他变化只会产生错误.思考?

自从我开始提问以来,不妨问另一个:由于lisp代码不应该使用交互功能,建议query-replace-regexp应该没问题,我是否正确?

Tre*_*son 7

您的替代品对我来说效果很好.

拿文字:

hi there mom
hi son!
Run Code Online (Sandbox Code Playgroud)

并使用您的建议尝试query-replace-regexp:

M-x query-replace-regexp (hi).*(mom) RET \1 \2! RET
Run Code Online (Sandbox Code Playgroud)

产量

hi mom!
hi son!
Run Code Online (Sandbox Code Playgroud)

我没有必要在括号前加一个反斜杠来让他们分组.也就是说,这会禁用能够匹配实际的括号......

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)))))
Run Code Online (Sandbox Code Playgroud)