如果有人能告诉我如何在 emacs 中执行此操作,它将节省我大量时间:我想做查找和替换,但保存我“找到”的内容以放入“替换”中。
基本上,我的文件中有一堆打印语句。我将 print 重新定义为 verboseprint(),当我的脚本运行时存在 verbose 标志时,它会进行打印。
但是,由于我使用的是 python 2.4,因此我在调用 print 语句时不使用括号:
print "Hello, world!"
我做了一个查找和替换来得到这个:
verboseprint "Hello, world!"
但是现在,我想做一个查找和替换来得到这个:
verboseprint ("Hello, world!")
这涉及以下步骤:
- 基于正则表达式查找字符串(我知道 emacs 可以做到)
- 让替换字符串占据原始字符串的一部分(我不确定 emacs 是否可以做到)
所以在伪代码中,当我进行“查找”时,我会搜索:
"verboseprint" + (characters until newline)
我会把它替换为
"verboseprint(" + (characters until newline) + ")"
这在 emacs 中可能吗?任何帮助,将不胜感激。谢谢!
最佳答案
这是一个可以完成此操作的快速 Emacs 命令。使用 M-x foo
或将 foo
绑定(bind)到一个键。
此处的正则表达式假定 verboseprint
之后到行尾的文本位于双引号字符内。如果没有,或者如果您想在此处或那里允许空格,请相应地调整正则表达式。
(defun foo (beg end)
"Wrap argument to `verboseprint` in parens.
If the region is active and nonempty then do it throughout just the region.
Otherwise do it throughout the buffer."
(interactive "r")
(unless (and transient-mark-mode mark-active (> end beg))
(setq beg (point-min)
end (point-max)))
(unless (<= beg end) (setq beg (prog1 end (setq end beg))))
(goto-char beg)
(replace-regexp "verboseprint \"\\(.*\\)\"$"
"verboseprint (\"\\1\")"
nil beg end))
您还可以仅使用 C-M-%
(query-replace-regexp
) 执行相同的操作。在这种情况下,您不必使用双反斜杠。
关于python - 如何在 emacs 中进行特殊的正则表达式查找和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38022680/