简体   繁体   English

Emacs查询替换文本转换

[英]Emacs query-replace with textual transformation

I want to find any text in a file that matches a regexp of the form t [AZ] u (ie, a match t followed by a capital letter and another match u , and transform the matched text so that the capital letter is lowercase. For example, for the regexp x[AZ]y 我想在文件中找到与t [AZ] u形式的正则表达式匹配的任何文本(即匹配t后跟大写字母和另一个匹配u ,并转换匹配的文本,使大写字母为小写。例如,对于正则表达式x[AZ]y

xAy

becomes

xay

and

xZy

becomes

xzy

Emacs' query-replace function allows back-references, but AFAIK not the transformation of the matched text. Emacs的query-replace功能允许反向引用,但AFAIK不是匹配文本的转换。 Is there a built-in function that does this? 是否有内置功能可以做到这一点? Does anybody have a short Elisp function I could use? 有没有人有我可以使用的简短Elisp功能?

UPDATE UPDATE

@Marcel Levy has it: \\, in a replacement expression introduces an (arbitrary?) Elisp expression. @Marcel Levy有它: \\,在替换表达式中引入了(任意?)Elisp表达式。 Eg, the solution to the above is 例如,上面的解决方案是

M-x replace-regexp <RET> x\([A-Z]\)z <RET> x\,(downcase \1)z

It looks like Steve Yegge actually already posted the answer to this a few years back: "Shiny and New: Emacs 22." 看起来Steve Yegge几年前已经发布了这个答案: “Shiny and New:Emacs 22.” Scroll down to "Changing Case in Replacement Strings" and you'll see his example code using the replace-regexp function. 向下滚动到“更换字符串中的更改大小写”,您将看到使用replace-regexp函数的示例代码。

The general answer is that you use "\\," to call any lisp expression as part of the replacement string, as in \\,(capitalize \\1) . 一般的答案是你使用“\\”来调用任何lisp表达式作为替换字符串的一部分,如\\,(capitalize \\1) Reading the help text, it looks like it's only in interactive mode, but that seems like the one place where this would be most necessary. 阅读帮助文本,看起来它只是在交互模式下,但这似乎是最需要的地方。

An alternative to qrr in this case is recording a macro and replaying it. 在这种情况下,qrr的替代方法是录制宏并重放它。 (isearch-forward-regexp, select the character, downcase-region.) I find on the fly macros easier, since you get immediate feedback if your regexp is wrong. (isearch-forward-regexp,选择字符,downcase-region。)我发现动态宏更容易,因为如果正则表达式错误,你会得到即时反馈。

I'd do this with a macro as well, but only because executing code from within a replacement string for a regular expression is very unintuitive to me. 我也用宏来做这件事,但这只是因为在正则表达式的替换字符串中执行代码对我来说非常不直观。 If you're writing a batch script or something that needs to go very fast, \\, is certainly the way to go. 如果您正在编写批处理脚本或需要非常快的东西,\\,肯定是要走的路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM