Dot and newline
By default the dot matches any character except line terminators (\n, \r and, in JavaScript, \u2028 and \u2029). To make it match newlines too, add the s flag (dotAll) in JavaScript or re.S / re.DOTALL in Python, or use [\s\S], which works in every engine.
Syntax
/a.b/s [\s\S] Python: re.compile(p, re.S)Examples
/start.*end/.test("start\nend")Result: false
/start.*end/s.test("start\nend")Result: true
The s flag lets the dot cross the line break.
/start[\s\S]*end/.test("start\nend")Result: true
[\s\S] is whitespace or non-whitespace, so anything at all.
"<p>a\nb</p>".match(/<p>(.*?)<\/p>/s)[1]Result: "a\nb"
Common mistakes
- Wondering why a multi-line block never matches: the dot stopped at the first newline. Add the s flag.
- Confusing m with s: m changes what ^ and $ match, s changes what the dot matches.
- Writing (.|\n)* to cross lines, which backtracks badly on long input; use [\s\S]* or the s flag.
- Using the s flag in an engine that lacks it (older browsers before 2018, some SQL dialects); [\s\S] is the portable fallback.
Practice Dot and newline
These drills check your answer on live data, free, no account needed.
- The dot matches one characterThe whole line must match. Match three-character lines that start with h and end with t, with any single character in the middle.
- Multiline flag: TODO linesEach test is a block of several lines. Capture the text after TODO: on every line that starts with TODO: (TODO, colon, space).
- Lazy vs greedy: the first quoted textCapture the text inside the first pair of double quotes on the line in group 1. It can be empty.
Questions
What does the s flag do in regex?
It makes the dot match every character, including \n and \r. JavaScript calls it dotAll and exposes it as regex.dotAll.
How do I match across multiple lines in Python?
Pass re.S (or re.DOTALL): re.search(r"start.*end", text, re.S). Without it, the dot stops at each newline.
Does the dot match \r?
No. Carriage return is a line terminator, so a Windows line ending (\r\n) stops the dot twice. The s flag or [\s\S] handles both.
Related
- Regex flagsWhat each JavaScript regex flag does (case-insensitive, global, multiline, dotAll, unicode, sticky), how to set them, and the lastIndex trap with g and test.
- Lazy vs greedyHow greedy quantifiers overshoot, how adding ? makes them lazy, why a negated class is often better than .*?, and the performance and newline traps.
- Regex for whitespaceHow \s matches spaces, tabs and newlines, trimming leading and trailing whitespace, collapsing repeated spaces, splitting on whitespace, and detecting blanks.
- Character classesWhat a character class matches, how ranges and negation work, what \d \w \s and their uppercase opposites mean, and what the dot does and does not match.
Previous: Escaping special charactersNext: Negated character class