appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Literals and character classes

Lesson 1 of 38 minBeginner

The building blocks: plain characters, the dot, classes and shortcuts.

A regular expression (regex) is a pattern that describes a set of strings. Most characters match themselves: cat matches the text "cat". The power comes from special symbols.

PatternMatchesExample
.Any one character except a newlinec.t matches cat, cut, c9t
[abc]One of the listed charactersgr[ae]y matches gray and grey
[a-z]A range[0-9] matches one digit
[^abc]Any character not listed[^0-9] matches a non-digit
\dA digit, like [0-9]\d\d matches 42
\wLetter, digit or underscore\w\w matches a1
\sWhitespace (space, tab, newline)a\sb matches "a b"

Escaping

To match a special character literally, put a backslash before it: \. matches an actual dot and \$ a dollar sign. Inside [...] most symbols are already literal.

NoteIn many languages a backslash in a string must itself be escaped, so \d is written "\\d". Raw strings such as Python r"\d" avoid that.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. Which pattern matches both "gray" and "grey"?
2. What does \d match?
3. How do you match a literal dot?
4. What does [^0-9] match?

Key terms