【问题标题】:How to search/replace expressions with parantheses in emacs?如何在emacs中用括号搜索/替换表达式?
【发布时间】:2013-12-29 03:35:54
【问题描述】:

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

\mathrm{\gamma \cdot x_0}

\gamma \cdot x_0

仅删除 \mathrm{ 很容易,但我还需要删除右括号。如何在 emacs 中做到这一点?

非常感谢,

恩诺

【问题讨论】:

    标签: search emacs replace latex


    【解决方案1】:

    您可以使用反向引用来解决这个问题。运行

    M-x query-replace-regexp

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

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

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


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

    【讨论】:

    • 如果不能有其他花括号嵌套在您要匹​​配的花括号中,您可能更喜欢{\(.*?\)} 来匹配花括号及其内容,而无需具体说明内容可以。 *?* 的非贪婪版本。
    • 也许\mathrm 用于以罗马字母设置度量单位(例如它是标准),出于任何原因,您必须将其更改为普通字体。速度的单位是\frac{m}{s}。但是,\mathrm{\frac{m}{s}} 参数中已经有了大括号。在这种情况下,您的正则表达式将匹配 \mathrm{\frac{m},这很危险。因此,我更喜欢下面的答案,它将\mathrm 背后的全部性别作为最后一组。
    【解决方案2】:

    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)))
    

    这应该是一个相当不错的功能。不仅用于替换像

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

    \frac{\gamma}{x_0}
    

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

    doSomethingUseless(x+somethingUseful(y))
    

    x+somethingUseful(y)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 1970-01-01
      • 2011-10-16
      • 2012-03-14
      • 1970-01-01
      • 2019-10-25
      相关资源
      最近更新 更多