Literals and character classes
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.
| Pattern | Matches | Example |
|---|---|---|
. | Any one character except a newline | c.t matches cat, cut, c9t |
[abc] | One of the listed characters | gr[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 |
\d | A digit, like [0-9] | \d\d matches 42 |
\w | Letter, digit or underscore | \w\w matches a1 |
\s | Whitespace (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.
Try it
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.