42

In Emacs regex, \n doesn't match a new line character \n.

  1. Am I correct that $ matches the position between a new line character and the character right before the new line character. e.g. for a string abc\n, $ matches the position between c and \n?
  2. What is the regex that matches \n?
beaver
  • 103
  • 5
Tim
  • 5,007
  • 7
  • 32
  • 61
  • 3
    Could you provide a minimum working example? Maybe I'm missing something, but (re-search-forward "\n") works fine for me. – Dan Feb 25 '15 at 00:37
  • 1
    Your file might use \r\n for new lines and it may be that you need to include \r in your regexp, so abc\r\n instead of abc\n. – Jordon Biondo Feb 25 '15 at 15:53
  • @Dan: C-M-s and M-x occur both match \n to n. my buffer is in Fundamental mode. This happens to any text, so any text with new line or letter n is a working example – Tim Feb 27 '15 at 02:17
  • 1
    @Jordon: C-M-s and M-x occur both match \r\n to rn – Tim Feb 27 '15 at 02:18
  • 1
    @Tim, yes because if you are entering them interactively you'd need to do a quoted inserts, C-q C-m, and C-q C-j respectively. You could enter \r\n if you were entering them into a lisp string. – Jordon Biondo Feb 27 '15 at 03:27
  • @Dan The string you used, "\n", consists of a single newline character, which certainly matches the newline character! If you wanted to prove that the two character sequence \n matches a newline, you'd need to escape the backslash in the string, i.e., to use (re-search-forward "\\n"). If you do that you'll see that \n matches the letter n. – Omar Jul 11 '19 at 19:17
  • @Jordon: (looking-at "\r?\n") matches both line styles. – Devon Jan 04 '23 at 19:41

2 Answers2

35
  1. Yes. $ matches the end of the line, not the newline character which comes after the end of the line.
  2. Do C-M-s C-q C-j. C-q is the default binding for quoted-insert and works in the minibuffer too. This expression literally searches for a newline: C-j.
Kaushal Modi
  • 25,651
  • 4
  • 80
  • 183
  • 1
  • are you saying the new line character can not be represented as an escape sequence in Emacs regex?
  • – Tim Feb 25 '15 at 00:01
  • 3
    Whether searching for a newline interactively or via elisp (e.g. (looking-at "^J") where ^J is inserted by C-q C-j), the C-q C-j approach always works. But when using elisp functions like the same looking-at \n works too; M-: (looking-at "\n") RET will eval to true if the cursor is at the end of the line (and there's a newline after that). – Kaushal Modi Feb 25 '15 at 00:09
  • 3
    Just to mention, if using regexp-builder, you're able to recognize a new line with [\n]. – Nsukami _ Feb 25 '15 at 00:29
  • 1
    @Nsukami_: C-M-s and M-x occur both match [\n] to n. – Tim Feb 27 '15 at 02:19