Emacs正则表达式替换 [英] Regex replacement with Emacs
问题描述
我正在尝试使用正则表达式搜索和替换。
假设我有一个 foreach(foo1.txt,foo2.txt,foo3.txt,foo4.txt)
。
我想把每个项目放在列表中。
Suppose I have a foreach(foo1.txt, foo2.txt, foo3.txt, foo4.txt)
.
And I want to put " around each item in the list.
我认为 - 从文档 - 这个正则表达式将工作
(foo [1-4] \.txt) - >\&
。
I thought- from the documentation - that this regex would work
(foo[1-4]\.txt) -> "\&"
.
但是不,我做错了什么?
But it doesn't. What am I doing wrong?
推荐答案
请注意,括号和括号需要转义(额外的斜杠) 搜索 regexp,但不在替换 regexp。
Note that brackets and parentheses need escaping ("extra slashes") in a search regexp, but not in the replace regexp.
转义是必需的,因为lisp-parser看到正则表达式引擎之前的正则表达式。
The escapes are required because the lisp-parser is seeing the regex prior to the regex engine.
但是,如果您以编程方式(而不是交互式输入)编写,则需要转义转义!ay-yi- yi ....
But, if you're writing programmatically (as opposed to interactive entry), you need to escape the escapes! ay-yi-yi....
interactive:
M-x replace-regexp RET \(obj.method(.*)\{1\}\) RET trim$(\1)
programmatic:
(replace-regexp "\\(obj.method(.*)\\{1\\}\\)" "trim$(\\1)")
转义的括号被转义,因为它们是分组的,未转义的括号是文字括号。
the escaped parens are escaped because they are grouping, the unescaped parens are literal parens.
您可能想查看 Emacs Wiki Regex Crash Course 和 Steve Yegge的有效Emacs正则表达部分。
这篇关于Emacs正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!