如何在emacs中用括号搜索/替换表达式?

时间:2013-12-11 08:46:33

标签: search emacs replace latex

我有一些Latex代码,其中包含许多数学表达式,包含在\ mathrm {}中。我想删除表达式周围的\ mathrm {}代码,最好使用emacs。例如,我想替换

\mathrm{\gamma \cdot x_0}

\gamma \cdot x_0

删除\ mathrm {只是很简单,但我还需要删除结束括号。我怎么能在emacs中这样做?

非常感谢,

恩诺

2 个答案:

答案 0 :(得分:7)

您可以使用返回引用来解决此问题。运行

M-x query-replace-regexp

并在第一个提示符处输入\\mathrm{\([\a-z0-9_ ]+\)},在第二个提示符处输入\1

query-replace-regexp的默认键绑定是 C-M - %

\1是要替换的正则表达式中第一个带括号的组\([\a-z0-9_ ]+\)的后向引用。该组以大括号之间的内容为目标。所以你要说的是,对于任何要替换的正则表达式,你只想保留那些内容。


有关替换正则表达式的更多信息可以在here或Emacs手册的相应info节点中找到。

答案 1 :(得分:2)

命令query-replace-regexp非常灵活。您可以将replace-re-search-function设置为您自己的搜索功能。 在此基础上,以下lisp代码定义了一个新命令query-replace-re+sexp,它用于搜索正则表达式,但在匹配中包含尾随性别。

在评估下面的defun后,您可以使用M-x query-replace-re+sexp作为查询替换功能。在您的示例中,输入为“from”-string \\\\mathrm和“replace-with”-string \\1。在那里,表达式\\1指的是由尾随的sexp(没有分隔符)产生的附加子表达式。

(defun re+sexp-search-forward (regexp bound noerror)
  "Search forward for REGEXP (like `re-search-forward')
but with appended sexp."
  (when (re-search-forward regexp bound noerror)
    (let ((md (match-data))
      bsub esub)
      (setq bsub (1+ (scan-sexps (goto-char (scan-sexps (point) 1)) -1))
        esub (1- (point)))
      (setcar (cdr md) (set-marker (make-marker) (point)))
      (setq md (append md (list (set-marker (make-marker) bsub)
                (set-marker (make-marker) esub))))
      (set-match-data md)
      (point))))

(defun query-replace-re+sexp ()
  "Like `query-replace-regexp' but at each match it includes the trailing sexps
into the match as an additional subexpression (the last one)."
  (interactive)
  (let ((replace-re-search-function 're+sexp-search-forward)) (call-interactively 'query-replace-regexp)))

这应该是一个非常好的功能。不仅用于替换像

这样的LaTeX结构
\mathrm{\frac{\gamma}{x_0}}

\frac{\gamma}{x_0}

但也适用于程序文本中的替换。例如,替换函数调用,如

doSomethingUseless(x+somethingUseful(y))

x+somethingUseful(y)
相关问题