tags:

views:

179

answers:

4

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?

+2  A: 

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

simao
+2  A: 

Emacs regexps always catch me out, cos they're not Perl:

\(foo[1-4]\.txt\)

You need to backslash the brackets in Emacs.

ijw
+1  A: 

You already got the right answer about the regexp, but in this case it would probably be easier to use macros instead. Put the point at the beginning of the first name, and type:

C-x ( " M-f M-f " C-f C-f C-x )

That is, start recording macro, insert quote, go two words forwards, insert quote, go two characters forwards for next element, and stop recording macro.

Then run the macro with C-x e. To repeat, just hit e again.

(In Emacs 23, you can use F3 instead of 'C-x (', and F4 instead of both 'C-x )' and 'C-x e'.)

legoscia
+3  A: 

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.

Michael Paulukonis
Helpful, but a little scary. "escape the escapes". Meep.
Paul Nathan