I would like to replace a two-line string not ending in digit with a one line string. For example, replacing the following two-line string:

Extensions of the Single—Sa1e
Model 414

With a one line string:

Extensions of the Single—Sa1e Model 414

Using M-x replace-regexp.

My regex pattern to match is [^[:digit:]]^J, but I don't know how to capture the non digit part and then refer it in the replace string. How can I do this? Also, how can I specify the new line character?

2 Answers 2


Type the newline char using C-q C-j. Capture parts of the match that you want using regexp groups. Reuse such group matches using \N syntax.

M-x replace-regexp RET \([^:digit:]]\) C-q C-j \(.+\) RET \1 \2 RET

So you enter 3 things, with RET: the command name, the regexp, and the replacement. The replacement uses \N syntax to reuse groups.

If you want to write a command that does this, you write a quick-and-dirty one that just calls what is written above (with backslashes doubled and with "\n" in place of C-q C-j). But if you want to write a command as it should be written, you would use write a loop that calls re-search-forward to find a match and then calls replace-match to replace it. See the Elisp manual, nodes Regexp Search and Replacing Match.

  • Thanks. (1) how can I specify that when M-x replace-regexp? (2) How can I run your function?
    – Tim
    Dec 2, 2014 at 23:12
  • I edited the answer to make it clear. You don't want to use replace-regexp in Lisp code anyway. Interactively, you don't double the backslashes, and you use C-q C-j to insert a newline char in the minibuffer.
    – Drew
    Dec 3, 2014 at 0:54
  • Thanks. How can I run your original elisp function foo on a buffer of text?
    – Tim
    Dec 3, 2014 at 1:00
  • Put point before the text to transform, and use M-x foo RET. It was just intended as a short way to show how to use the arguments, but showing it probably confused more than it clarified.
    – Drew
    Dec 3, 2014 at 1:07
  • But do I need to run the definition of foo first, so that M-x foo RET will work? How to?
    – Tim
    Dec 3, 2014 at 1:17

This does not answer your question, since you asked for a regexp to do it, but I think it's worth mentioning that the same can be done easily using a keyboard macro. Start recording with F3, search for the regexp with C-s M-r [^[:digit:]]^J <RET>, press Backspace to join the lines and F4 to finish the macro. Then repeat by pressing F4 until all lines are joined.


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.