Skip to content
shellhacks.dev
Regular Expressions

Match any character including newline

A dot does not match a newline by default. Turn on DOTALL, written (?s) in PCRE and Python, or use [sS] when the engine has no such flag.

1 min read
Summarize in AI

A pattern with .* stops at the end of a line, and you want it to run across several.

Python
import re

text = "BEGIN\nline one\nline two\nEND"
print(re.search(r"BEGIN.*END", text))
print(re.search(r"BEGIN.*END", text, re.DOTALL).group().count("\n"))
print(re.search(r"(?s)BEGIN.*END", text).group().count("\n"))
print(re.search(r"BEGIN[\s\S]*END", text).group().count("\n"))
Text
None
3
3
3

Outside of the DOTALL mode a dot matches any character except the newline, which the re documentation states. The flag can be passed as an argument or switched on inside the pattern as (?s). The last form, a class of whitespace together with non-whitespace, is the portable one, since together they cover every character in any engine.

The name of the flag differs: JavaScript uses s, Perl s, and Ruby calls it m. grep works line by line, so it needs -z with -P to see a newline at all. A greedy .* with DOTALL swallows everything to the last END, so use .*? when you want the shortest span.

Taggedregex
Share

More snippets

Regular Expressions

Match a quoted string

Match a quoted string with a negated character class. An escaped quote inside the text ends the match early, and a PCRE alternation that pairs backslashes handles it.

1 min read
Regular Expressions

Match a semantic version

Match a semantic version with the pattern from semver.org, which runs in grep -E. It rejects leading zeros, a bare 1.2 and a v prefix, and takes pre-release tags.

1 min read
Regular Expressions

Match a UUID

Match a version 4 UUID with 8-4-4-4-12 hex groups, a 4 at the start of the third group and 8, 9, a or b at the start of the fourth. Add -i for uppercase.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.