代码之家  ›  专栏  ›  技术社区  ›  polyglot

如何将“(”替换为“\”(在regexp中,emacs/elisp flavor?

  •  2
  • polyglot  · 技术社区  · 14 年前

    标题问题。

    更具体地说,我已经厌倦了打字 \( 等。每次我想要在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)))))
    

    希望在“交互模式”下,能方便地忘记regexp中emacs的特性。除非我不能把regexp弄好…

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

    给予 \\(abc 而不是通缉犯 \(abc . 斜杠数量的其他变化只会产生错误。思想?

    既然我开始提问,不妨再问一个问题:既然lisp代码不应该使用交互式函数,那么建议 query-replace-regexp 应该没事吧,对吗?

    1 回复  |  直到 14 年前
        1
  •  7
  •   Trey Jackson    14 年前

    你的替代品对我很有效。

    接受课文:

    hi there mom
    hi son!
    

    并尝试用您的建议来替换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)))))