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!

1

1 Answer 1

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
2
  • 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, 2022 at 13:19
  • 1
    Thank you this answer and comment were both really helpful, and I've solved my particular problem. Aug 12, 2022 at 13:48

Your Answer

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

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