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

mce*_*nno 3 emacs search latex replace

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

\mathrm{\gamma \cdot x_0}
Run Code Online (Sandbox Code Playgroud)

\gamma \cdot x_0
Run Code Online (Sandbox Code Playgroud)

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

非常感谢,

恩诺

its*_*eyd 7

您可以使用反向引用来解决此问题.跑

M-x query-replace-regexp

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

默认的键绑定query-replace-regexpC-M-%.

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


有关替换正则表达式的更多信息可以在此处或在infoEmacs手册的相应节点中找到.

  • 如果没有其他花括号嵌套在你匹配的那些内,你可能更喜欢`{\(.*?\)}`来匹配花括号和它们的内容,而不需要具体说明是什么内容可以.`*?`是`*`的非贪婪版本. (3认同)

Tob*_*ias 5

该命令query-replace-regexp相当灵活。您可以设置replace-re-search-function自己的搜索功能。在此基础上,以下 lisp 代码定义了一个新命令query-replace-re+sexp,该命令搜索正则表达式,但将尾随的 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)))
Run Code Online (Sandbox Code Playgroud)

这应该是一个相当不错的功能。不仅用于替换 LaTeX 结构,例如

\mathrm{\frac{\gamma}{x_0}}
Run Code Online (Sandbox Code Playgroud)

\frac{\gamma}{x_0}
Run Code Online (Sandbox Code Playgroud)

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

doSomethingUseless(x+somethingUseful(y))
Run Code Online (Sandbox Code Playgroud)

x+somethingUseful(y)
Run Code Online (Sandbox Code Playgroud)