Learn regular expressions · Lesson 5
The dot and line breaks
The dot, ., matches any one character: a letter, a digit, a space, a symbol. (What one character is, is less simple than it sounds: see the box below.) h.t is an h, any character, and a t:
/h.t/g4 matches
hat , hit , h t , h-t , ht
Try it in Dotstar →
ht doesn’t match: the dot needs exactly one character.
Except a line break
By default the dot doesn’t match a line break. So .+ never runs past the end of a line, which is usually what you want:
/.+/g2 matches
first line
second line
Try it in Dotstar →
Two matches, one a line, not one across both.
The s flag
With the s flag (“single line”, or “dot all”) the dot matches line breaks too, so .+ takes the whole text:
/.+/gs1 match
first line
second line
Try it in Dotstar →
That’s useful for something that spans lines, like a block between two markers; a later lesson shows how to keep .* from taking too much when you do.
In other flavors
The flag has different names: s in JavaScript, PCRE2, Perl and Go ((?s)); re.DOTALL in Python; RegexOptions.Singleline in .NET; Pattern.DOTALL in Java. Ruby is the odd one: its m flag is the dot-all flag, and Ruby has no flag for what the others call m, because its ^ and $ always match at every line.
/.+/gmin each engine
one\ntwo
Ruby one\ntwo JavaScript, PCRE2 one two
Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.
Which characters count as a line break differs too. JavaScript’s dot leaves out \n, \r and the Unicode line and paragraph separators; Java’s also \u0085. Python’s and .NET’s leave out only \n, so in a text with Windows line endings (\r\n), .+ there takes the \r at the end of each line along with it, a classic source of stray characters:
/.+/gin each engine
one\r\ntwo
JavaScript, Java one two Python, .NET one\r two
Run in each engine itself, as Dotstar’s Compare runs them, when this page was checked.
PCRE2’s is chosen by the program that compiles the pattern (with a default from how PCRE2 was built, usually \n), and (*CRLF) or (*ANYCRLF) at the start of a pattern overrides it.
In other flavors
One character? In JavaScript without the u or v flag the dot matches one UTF-16 code unit, so an emoji, which takes two, needs two dots: "😄".match(/./g) finds two halves, and "😄".match(/./gu) one character. With u it’s one Unicode code point, which still isn’t always what a reader sees as one character: an accented letter can be a letter and a combining accent, and a flag or a family emoji several code points joined. .NET works in UTF-16 units too; Java, Python, Go, Rust and PCRE2 with UTF in code points; Swift’s Regex by default in characters as a reader sees them. Compare in Dotstar shows where it makes a difference.
A dot inside brackets
In a character class a dot is just a dot: [.] is the same as \.. Some people write [.] because it reads more clearly than a backslash, and in a string in code it needs no escaping.
← Character classes Anchors and word boundaries →