Match newlines with regex

How to match newlines with regex: LF vs CRLF, \r?\n and \R, why dot skips line breaks, dotall vs multiline flags, and what changes when text is copied or shared.

Matching a line break with a regular expression looks like a one-token job, but the right pattern depends on three things: which line-ending characters are actually stored in the text, which regex engine runs the pattern, and which flags are set. This review explains what a newline match really touches, where common patterns fail, and when you are better off not using regex at all.

Is a regex newline match right for your task?

For splitting, counting or replacing lines in text that may come from different systems, \r?\n is a sound default, and \R is the more complete choice in engines that support it. The main benefit is precision: you control exactly which characters count as a line break and what replaces them. The decisive tradeoff is portability. The same pattern can behave differently across engines and flag settings, and a pattern that works on one file can silently miss breaks in another without raising any error.

Plain text handling is preferable in three cases. If you only need a list of lines, a language's built-in line-splitting function is usually safer than a hand-written pattern; Python's str.splitlines, for example, recognizes a wider set of terminators than \n alone. If the destination already preserves line breaks as they are, no transformation is needed. And if a person will read or edit the result, collapsing or stripping breaks often destroys structure that a regex cannot restore later.

What a newline actually is

A regex works on stored characters, not on how text looks on screen. Two files that display identically can contain different line-ending bytes. The common forms are line feed (LF, U+000A), used by Unix-like systems including modern macOS; carriage return plus line feed (CRLF, U+000D U+000A), the Windows convention and the one used by many network protocols; and a lone carriage return (CR), used by classic Mac OS and still found in some older files. Unicode also defines next line (NEL, U+0085), line separator (U+2028) and paragraph separator (U+2029), which some engines treat as line terminators and others do not.

Newline patterns and what each one matches

Pattern | Matches | Watch out for
\n | LF only | Leaves a stray \r at the end of each line in CRLF text
\r\n | CRLF only | Misses every break in LF-only text
\r?\n | LF or CRLF | Misses lone CR and Unicode separators
(?:\r\n|\r|\n) | CRLF, CR or LF | Keep \r\n first; if \r comes first, one CRLF counts as two breaks
\R | Any line-break sequence, including Unicode separators | Supported in PCRE, Perl and Java 8+, not in JavaScript, Python's re module, .NET or Go
\s | Any whitespace, including line breaks | Also matches spaces and tabs, so it is not a newline test
[\s\S] | Any character at all | A portable stand-in for dot-all mode, mainly for older JavaScript

Why the dot skips line breaks, and the flag that changes it

By default, the dot metacharacter does not match a line break, so a pattern like start.*end will not span two lines. A dot-all flag (often called single-line mode) lifts that restriction. Engines also differ in which characters the dot excludes by default, which matters for text containing CR or Unicode separators.

Engine | Dot excludes by default | How to let dot match newlines
JavaScript | LF, CR, U+2028, U+2029 | s flag (ES2018 and later), or [\s\S] in older runtimes
Python re | LF only | re.DOTALL or inline (?s)
Java | LF, CR, CRLF, U+0085, U+2028, U+2029 | Pattern.DOTALL or inline (?s)
.NET | LF only | RegexOptions.Singleline or inline (?s)
PCRE / PHP | Depends on the configured newline convention, commonly LF | s modifier or inline (?s)
Go (RE2) | LF only | Inline (?s)

Multiline mode is a separate setting

Multiline mode (the m flag in most engines) changes only the anchors: ^ and $ match at the start and end of each line instead of only at the start and end of the whole input. It does not make the dot cross line breaks. The naming causes real confusion. .NET calls dot-all mode Singleline and anchor mode Multiline. Ruby's /m flag means dot-all, while its ^ and $ are always line anchors. Before copying a pattern between languages, check what each flag letter means in the target engine.

Anchors carry their own line-ending caveats. In Python, $ matches at the very end of the string and also just before a final trailing newline, even without multiline mode; \Z matches only the absolute end. In .NET multiline mode, $ matches before \n but not before \r, so with CRLF text the \r stays at the end of each matched line unless you add \r? to the pattern.

Checking examples against the mechanism

The following JavaScript snippets show the two most common surprises: a stray carriage return left behind by \n, and a dot that stops at a line break until the s flag is added. The results shown in the comments follow from the documented rules above.

const text = "first\r\nsecond\nthird";

text.split(/\n/);     // ["first\r", "second", "third"]
text.split(/\r?\n/);  // ["first", "second", "third"]

/first.second/.test("first\nsecond");   // false
/first.second/s.test("first\nsecond");  // true

Will the result survive copying and sharing?

Line endings can change in transit, so a pattern tested on one copy of the text may meet different bytes later. Git can convert line endings on checkout and commit depending on settings such as core.autocrlf. Editors may normalize endings when saving. The HTML specification normalizes textarea content to CRLF when a form is submitted, while the value a script reads in the browser uses LF. When behavior is puzzling, inspect the real bytes instead of trusting the display; with GNU coreutils, cat -A shows a carriage return as ^M before the $ that marks each line end.

Copying a pattern itself has pitfalls too. Inside a string literal in code or JSON, \n may be turned into an actual newline character before the regex engine sees it. That usually still matches, but it behaves differently from the escape sequence in some contexts, so raw strings (such as Python's r"...") make the intent clearer. Online regex testers and editor search boxes can also normalize line endings when you paste text into them; no specific tool was tested for this review, so do not assume a tester's result reflects the bytes in your actual file.

Line-oriented command-line tools add a further limit. grep and sed read input one line at a time and strip the newline before matching, so a pattern containing \n generally will not match across lines. Workarounds include GNU grep's -z option, sed's N command, or a scripting language that reads the whole input at once.

Readability is the last check. Replacing line breaks with spaces merges lists, addresses, verse and code into a single run of text, and screen readers and search indexes then receive that flattened version. Keep in mind the difference between stored characters and visual presentation: in HTML, ordinary text has its newlines collapsed into spaces by default CSS, so breaks that exist in the data only appear if the page uses white-space: pre-line (or similar) or real paragraph and line-break elements. For anything people will read, keep the breaks or convert them into proper structure rather than deleting them.

Gaps and limits of this review

No tool-specific tests were run for this article, and no measurements are reported. Engine behavior described here comes from documented language rules, which can vary by version and configuration, especially for older JavaScript runtimes without the s flag and for PCRE builds with a non-default newline setting. Verify any pattern in the exact engine, version and destination where it will run.

Quick checklist

  • Find out which line endings the input really contains before writing the pattern.
  • Use \r?\n for LF and CRLF, (?:\r\n|\r|\n) to include lone CR, or \R where the engine supports it.
  • Turn on dot-all mode only when the dot needs to cross lines; use multiline mode only when ^ and $ should match at each line.
  • Confirm what each flag letter means in the target language.
  • Test with the real file or payload, not a pasted copy.
  • Prefer built-in line-splitting functions when you only need a list of lines.
  • Keep or restructure line breaks in text meant for human readers.