0

I'm struggling with the basics of query-replace-regex after reading the manual.

I'm trying to replace lots of citations formatted like this: #123213213, foo bar

to #123213213\, foo bar

the numbers vary from instance to instance and can be of any length. They always start with a #. Foo bar can be numbers or text. I always want to replace only:

, --> \,

without changing the numbers or the foo bar.

I've tried emacs' regex builder, and I'm stuck at "\#[0-9]*,\s.*\} which doesn't work because it selects too much before the bit I want. Ideally, I'm looking for an answer that explains how it works. Thanks for your help!

user13495873
  • 113
  • 3
  • https://emacs.stackexchange.com/q/5568/454 explains some crucial things about `re-builder`. – phils Aug 12 '22 at 06:21

1 Answers1

1

Assuming the trailing arbitrary text can legitimately contain commas, so you can't safely replace every , with \, throughout:

  1. You don't need to escape the #.
  2. Based on your description, you don't need the \}
  3. (minor point) You always expect at least one digit in the leading number, correct? Use + rather than *.

Try this:

(query-replace-regexp "#\\([0-9]+\\), \\(.*\\)" "#\\1\\\\, \\2")

Interactively, you halve the backslashes:

#\([0-9]+\), \(.*\)
RET
#\1\\, \2
RET
Phil Hudson
  • 1,651
  • 10
  • 13
  • 1
    If you only reproduce the second match, you can omit it and only keep the `#\([0-9]+\),` part and replace with `#\1\\,`. – rsp Aug 12 '22 at 13:19
  • 1
    Thank you this answer and comment were both really helpful, and I've solved my particular problem. – user13495873 Aug 12 '22 at 13:48