Regex across multiple lines

Why . stops at a line break, the two ways to make a pattern span lines, how that differs from the confusingly named multiline flag, and what Windows line endings do to all of it.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

/<!--.*?-->/s

By default . matches any character except a line break, so a pattern such as <!--.*?--> finds one-line comments and silently misses the rest. The s flag, called dotall, changes that. It is supported by JavaScript (since ES2018), Python, PHP, .NET, Java and Perl, under different names.

The tester at the top of this page is loaded with this pattern and the example text. Edit either box to try your own.

How it works, token by token

PartMeaning
<!--The literal start of an HTML comment.
.*?Any characters, as few as possible. With the s flag, . also matches line breaks.
-->The literal end of the comment.

What it finds

Searching this text:

a <!-- one --> b <!-- two
lines --> c

finds 2 matches:

1. <!-- one -->
2. <!-- two
lines -->

Without the s flag: [\s\S]

Some tools have no dotall option, such as older JavaScript engines, many editors' search boxes and some database functions. A class that contains both whitespace and non-whitespace matches every character, line breaks included:

/<!--[\s\S]*?-->/

Searching this text:

a <!-- one --> b <!-- two
lines --> c

finds 2 matches:

1. <!-- one -->
2. <!-- two
lines -->

[\d\D] and [\w\W] work the same way. In JavaScript, [^] is a shorter spelling, but it is an error in most other engines, so avoid it in patterns you share.

Lazy, not greedy

Once . can cross lines, a greedy * runs to the last --> in the whole text and swallows everything in between:

/<!--[\s\S]*-->/

Searching this text:

a <!-- one --> b <!-- two
lines --> c

finds 1 match:

1. <!-- one --> b <!-- two
lines -->

The lazy *? stops at the first --> after each start. For large inputs a negated class is often clearer and faster still, when the closing delimiter is a single character: "[^"]*" for a quoted string spans lines without any flag, because [^"] already includes line breaks.

The m flag is something else

The multiline flag, m, does not let anything cross lines. It makes ^ and $ match at the start and end of every line instead of only at the ends of the whole text:

/^#+ .*$/m

Searching this text:

# Title
Some text
## Section
More text

finds 2 matches:

1. # Title
2. ## Section

The same pattern without it finds nothing, because $ only matches at the very end and . cannot reach it:

/^#+ .*$/

Searching this text:

# Title
Some text
## Section
More text

finds 0 matches:

EffectJavaScriptPythonPHPC# (.NET)
. matches line breakssre.DOTALL or re.SsRegexOptions.Singleline
^ and $ at each linemre.MULTILINE or re.MmRegexOptions.Multiline

.NET's names are the confusing ones: Singleline is the dotall flag, because it treats the text as a single line. The two flags are independent and can be combined.

Windows line endings

Text from Windows ends lines with \r\n, and engines disagree about what that means for ^, $ and .. JavaScript treats \r as a line terminator of its own, so it finds an empty "line" between the two characters. Python's . and $ only know about \n, so the \r ends up inside the match:

console.log(JSON.stringify('a\r\nb'.match(/^.*$/gm)));  // → ["a","","b"]
print(re.findall(r'^.*$', 'a\r\nb', re.MULTILINE))  # → ['a\r', 'b']

.NET behaves like Python here. The simplest fix is to normalise line endings first, replacing \r\n with \n, or to allow an optional \r before the $ in your pattern.

In JavaScript, Python, PHP and C#

JavaScript

const text = 'a <!-- one --> b <!-- two\nlines --> c';
for (const m of text.matchAll(/<!--.*?-->/sg)) console.log(m[0]);
// → <!-- one -->
// → <!-- two\nlines -->

Python

import re

text = 'a <!-- one --> b <!-- two\nlines --> c'
for m in re.finditer(r'<!--.*?-->', text, flags=re.DOTALL):
    print(m.group())
# → <!-- one -->
# → <!-- two\nlines -->

PHP

<?php
$text = "a <!-- one --> b <!-- two\nlines --> c";
preg_match_all('/<!--.*?-->/s', $text, $m);
foreach ($m[0] as $match) echo $match, "\n";
// → <!-- one -->
// → <!-- two\nlines -->

C#

using System;
using System.Text.RegularExpressions;

var text = "a <!-- one --> b <!-- two\nlines --> c";
foreach (Match m in Regex.Matches(text, @"<!--.*?-->", RegexOptions.Singleline)) Console.WriteLine(m.Value);
// → <!-- one -->
// → <!-- two\nlines -->

Python's re.findall returns the capture groups instead of the whole match when a pattern has groups, so re.finditer is the safer habit. In PHP, preg_match_all puts the whole matches in $m[0].

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

How do I make a regex match across multiple lines?

Turn on the dotall flag so that . matches line breaks: s in JavaScript and PHP, re.DOTALL in Python, RegexOptions.Singleline in .NET. Or use [\s\S] instead of . where no flag is available.

What is the difference between the s and m flags?

s lets . match line breaks. m makes ^ and $ match at the start and end of each line. They solve different problems and can be used together.

Why does my regex match too much when it spans lines?

A greedy .* runs to the last possible end. Use the lazy .*? to stop at the first one.