Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex replacement with Emacs

Tags:

regex

emacs

I am trying to do a search and replace with regexs.

Suppose I have a foreach(foo1.txt, foo2.txt, foo3.txt, foo4.txt). And I want to put " around each item in the list.

I thought- from the documentation - that this regex would work (foo[1-4]\.txt) -> "\&".

But it doesn't. What am I doing wrong?

like image 808
Paul Nathan Avatar asked Jun 29 '09 21:06

Paul Nathan


2 Answers

Note that brackets and parentheses need escaping ("extra slashes") in a search regexp, but not in the replace regexp.

The escapes are required because the lisp-parser is seeing the regex prior to the regex engine.

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.

You might want to check out the Emacs Wiki Regex Crash Course and Steve Yegge's Effective Emacs regex section.

like image 175
Michael Paulukonis Avatar answered Oct 07 '22 10:10

Michael Paulukonis


Try something like this \(foo[1-4]\.txt\)

like image 29
simao Avatar answered Oct 07 '22 10:10

simao