4

One of my collaborators has written a long rtf document that goes like this.

a paragraph of text

(1) some text

another paragraph or two of text

(2) some text

another paragraph or two of text

And so on. I've opened the file in emacs and I was trying to run replace-regexp to turn the parenthesized numbers into \exx{ , where \exx{ is a newcommand I have defined in the preamble and will take turn of sequential numbering. However, if I type

M-x replace-regexp ^([0-9]\{1,2\}) RET \exx\{ RET

Then I get the following error message

Invalid use of `\' in replacement text

I have tried using this alternative expression

M-x replace-regexp ^([0-9]\{1,2\}) RET \\\\exx\\{ RET

But this simply replaces (1) and subsequent numbers with \\exx\{ , which is not what I want. Every other combination of backslashes that I have tried returns the Invalid use of \ in replacement text error.

I know I can use sed to get regexp replacement I want, but that is not the issue. I'm asking this question here because I want to understand how to do this particular type of regexp replacement internally to emacs.

6
  • 2
    Single escape: \\exx\\{
    – abo-abo
    May 19, 2015 at 11:39
  • No, this replaces (1) with \exx\{ , which is not what I want. I want the opening curly bracket without a preceding backslash.
    – Koldito
    May 19, 2015 at 11:47
  • 1
    Fine, \\exx{.
    – abo-abo
    May 19, 2015 at 11:48
  • 1
    Yes, that works, thanks. To recap, my mistake was that I thought I had to escape the curly bracket as well in the replacement text
    – Koldito
    May 19, 2015 at 11:49
  • 1
    Your regexp seems to have an extra closing parenthesis. Is this also the case when you try it in Emacs, or is this a copy-and-paste error?
    – wvxvw
    May 19, 2015 at 11:49

1 Answer 1

7

To make clear the accepted answer in the comments:

M-x replace-regexp ^([0-9]\{1,2\}) RET \exx\{ RET
                                           ^^

should be

M-x replace-regexp ^([0-9]\{1,2\}) RET \\exx{ RET
                                           ^

More generally, special symbols like {, |, ( that need to be escaped in the regular expression search string, do not get escaped in the replacement string. Only '\' has to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.