views:

467

answers:

5

How are \r and \n different. I think it has something to do with Unix vs. Windows vs. Mac, but I'm not sure how exactly they're difference, and which to search for/match in regexes.

+28  A: 

They're different characters. \r is carriage return, and \n is linefeed.

On "old" printers, \r sent the print head back to the start of the line, and \n advanced the paper by one line. Both were therefore necessary to start printing on the next line.

Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r to move to the start of the line and overwrite the existing text.

More importantly, Unix tends to use \n as a line separator; Windows tends to use \r\n as a line separator and Macs (up to OS 9) used to use \r as the line separator. (Mac OS X is Unix-y, so uses \n instead; there may be some compatibility situations where \r is used instead though.)

For more information, see the Wikipedia newline article.

Jon Skeet
+1 for old people. Terminal output used to directly control a glorified electronic terminal (your TTY before those fancy CRT displays). Hence, we get wonderful artifacts of those in the carriage return and newline characters (both of which might be needed, as Jon Skeet mentioned) and things like \a "bell", \b "backspace" (not to be confused with "delete"), and all the other control characters needed to communicate with a tty.
erjiang
I don't think Jon is *that* old!
Mehrdad Afshari
Another +1 for old people. You can still hit Ctrl+G on a windows command prompt, hit enter, and the PC speaker will beep. That's left over from ancient times.
Crappy Coding Guy
@Crappy Coding Guy really? On Vista, it just says "'' is not recognized as an internal or external command"
Wallacoloo
@Wallacoloo: in Widnows 7 i get same error but WITH BEEP ;-)
Svisstack
A: 

\r is Carriage Return; \n is New Line (Line Feed) ... depends on the OS as to what each means:

http://www.go4expert.com/forums/showthread.php?t=8021

Nathan Loding
+3  A: 

In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).

Josip Medved
Mac OS X systems use LF by default (since it is based on BSD Unix).
dreamlax
+2  A: 

In addition to @Jon Skeet's answer:

Traditionally Windows has used \r\n, Unix \n and Mac \r, however newer Macs use \n as they're unix based.

Greg
+1  A: 
  • "\r" => Return
  • "\n" => Newline or Linefeed (semantics)

  • Unix based systems use just a "\n" to end a line of text.

  • Dos uses "\r\n" to end a line of text.
  • Some other machines used just a "\r". (Commodore, Apple II, Mac OS prior to OS X, etc..)
NoMoreZealots
+1 for Commodore and Apple II!
Al
I think you have your \r-only and \n-only mixed up. \n is unix.
cyberconte
Oops! You're right, I'll fix it.
NoMoreZealots