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.

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.