【问题标题】:Emacs: regular expression replacing to change case (in scripts)Emacs:正则表达式替换以更改大小写(在脚本中)
【发布时间】:2012-12-04 15:09:43
【问题描述】:

这与 Emacs: regular expression replacing to change case

我的另一个问题是我需要编写搜索替换脚本,但 "\,()" 解决方案仅在以交互方式使用 (emacs 24.2.1) 时才有效(对我而言)。在脚本中它给出了错误:“在替换文本中无效使用\'”。

我通常会在需要时将“执行替换”写入某些要加载的文件。比如:

(执行-替换"<\\([^>]+\\)>" "<\\,(downcase \1)>" t t nil 1 nil (point-min) (point-max))

应该可以调用一个函数来生成替换(pg 741 of the emacs lisp manual),但是我尝试了以下的许多变体,但没有运气:

(defun myfun ()
    (downcase (match-string 0)))

(perform-replace "..." (myfun . ()) t t nil)

谁能帮忙?

【问题讨论】:

    标签: regex emacs replace


    【解决方案1】:

    \,() 这样的构造只允许在对query-replace 的交互调用中使用,这就是Emacs 在你的情况下抱怨的原因。

    perform-replace 的文档提到你不应该在 elisp 代码中使用它,并提出了一个更好的替代方案,我们可以在此基础上构建以下代码:

    (while (re-search-forward "<\\([^>]+\\)>" nil t)
      (replace-match (downcase (match-string 0)) t nil))
    

    如果您仍想以交互方式向用户查询替换,则像您所做的那样使用perform-replace 可能是正确的做法。您的代码中有几个不同的问题:

    1. elisp manual 中所述,替换函数必须采用两个参数(您在 cons 单元格中提供的数据和已经进行的替换次数)。

    2. 1234563 .
    3. 需要引用cons单元格(myfun . nil),否则会被解释为函数调用,过早地求值。

    这是一个工作版本:

    (let ((case-fold-search nil))
      (perform-replace "<\\([^>]+\\)>"
                       `(,(lambda (data count)
                           (downcase (match-string 0))))
                       t t nil))
    

    【讨论】:

    • nop,我需要查询(y/n/!等)和高亮执行替换的功能(我不想用 y-or-n-p + highlight-regexp 重新实现它或类似的)
    • 您可能希望编辑您的问题以反映此约束。无论如何,我提出了一个基于perform-replace 的解决方案,应该可以满足您的要求。
    【解决方案2】:

    C-h f perform-replace 说:

    Don't use this in your own program unless you want to query and set the mark
    just as `query-replace' does.  Instead, write a simple loop like this:
    
      (while (re-search-forward "foo[ \t]+bar" nil t)
        (replace-match "foobar"))
    

    现在"&lt;\\,(downcase \1)&gt;" 需要替换为构建正确字符串的 Elisp 表达式,例如 (format "&lt;%s&gt;" (downcase (match-string 1)))

    如果您确实需要查询和其他内容,那么您可能想尝试:C-M-% f\(o\)o RET bar \,(downcase \1) baz RET,然后是C-x RET RET,看看在交互式调用期间构造了哪些参数。

    您会发现(如果您单击C-h f perform-replace 中的replace.el 以查看函数的源代码会更好),replacements 参数可以采用 (FUNCTION . ARGUMENT) 形式。更具体地说,该代码包含一个提供一些详细信息的注释:

    ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
    ;; containing a function and its first argument.  The function is
    ;; called to generate each replacement like this:
    ;;   (funcall (car replacements) (cdr replacements) replace-count)
    ;; It must return a string.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多