Character Classes: Ranges, Shorthand Classes, and “ë”
You open the next message on the Sorting Station console. In ticket 18, Alyona writes: “Autocorrect keeps mixing things up: Zoë, Zoe, and Zoë Miller are all me, Alyona.” The Commandant asks you to find her in the export. You also discover that Alyona herself has somehow ended up on the “suspicious names” list.
QUERY: Before you suspect the person, check the sieve. Letters like “ë” get left out of checks like these more often than you'd expect.
A card with the previous pattern, cat, is still on the desk. It finds lowercase “cat” but not capitalized “Cat.” You could make the whole pattern case-insensitive, but here we need a more precise approach: allow several options in just one position.
We'll start with that position. Then we'll use the same idea for digits in codes, extra characters in phone numbers, and spaces that are easy to miss by eye.

One position, several allowed characters
Take the word Cat. The pattern cat won't find it because the first letter has a different case. If both “c” and “C” are allowed in the first position, list them inside square brackets: [cC]at.
Read the pattern from left to right. [cC] controls the first position: either “c” or “C” can appear there. Next must come a lowercase a, followed by a lowercase t.
Check three strings by hand.
cat: the first c is in [cC], then a and t match. We get cat.
Cat: the first C is also allowed, and the remaining letters match. We get Cat.
CAT: C passes the first check, but then the pattern expects a lowercase a and finds A. There is no match. A character class affects only the position where it appears.
If we used the ~* operator from the first lesson, case would be ignored throughout the expression. In [cC]at, we explicitly allow two options only for the first letter.
A common mistake is writing [cat]. It looks like a word, but letters inside square brackets don't form a sequence. [cat] means a single c, a, or t. So in the string cat, a global marker finds three separate matches: cat.
Now take the string scatter. The pattern cat finds scatter. [cat] marks individual matching letters inside the string. Square brackets always occupy one position.
In a long text, nearby words can be distracting, so we'll keep just four short strings and focus on the character class itself.
Predict the result first. For [cC]at, which of cat, Cat, CAT, and scatter contain a match? For scatter, don't test the whole string; check whether it contains a matching fragment.
A range instead of a long list
The Commandant opens the server log. The addresses contain codes such as KM-2025-000311 and KM-2024-002468. For now, the task is simple: find KM- followed immediately by one digit.
You could write KM-[0123456789]. That pattern works, but ten digits in a row are awkward to read and check. [0-9] says the same thing more compactly: one digit from 0 through 9, including both endpoints.
Read KM-[0-9] position by position. First comes K, then M, then a hyphen. The final part, [0-9], occupies one position and accepts one digit.
In the string KM-2025-000311, KM- matches first, then [0-9] takes the 2. The pattern ends there, so we get KM-2025-000311. The remaining 025-000311 isn't part of the match: we don't yet have a way to match several digits in a row.
What happens with the string KM-X? K, M, and the hyphen match, but the last position contains X instead of a digit. A partial match doesn't count, so there is no result.
Ranges work for letters too. [a-z] chooses one lowercase Latin letter, and [A-Z] chooses one uppercase Latin letter. You can put several ranges in one character class: [a-zA-Z0-9]. Despite the length of the notation, the match is still exactly one character.
Take the string A7_. [a-zA-Z0-9] matches A first, then matches 7 separately, and skips _. With a global search, you'll see A7_.
Before you run anything, work out the result without SQL. There are three strings: A, 7, _. The pattern [a-zA-Z0-9] is tested against each one separately.
For A, the answer is immediate: it falls in the range A-Z. Finish the check for 7 yourself. Which of the three ranges contains this digit? And what does that mean for _?
After you've answered, run the query. Look at both true and false and at the character class itself: it contains three ranges, and underscore isn't one of them.
Why “ë” gets left out
Return to Alyona. Contact 3 is stored as Zoë Miller. The letters look ordinary, so a natural first idea is to write lowercase Latin letters as [A-Za-z] and uppercase ones as [A-Z].
This check fails on ë. In our PostgreSQL environment, [A-Za-z] doesn't include ë, and [A-Z] doesn't include Ë.
Look at Zoë character by character. The lowercase range isn't checking uppercase Z right now. o falls inside [A-Za-z]. The next character, ë, does not. e and e match again. If you replace every matched lowercase letter with a dot, you get something like ··ë: ë remains visible among the replacements.
The diagram makes the reason easier to see. [A-Za-z] defines a range from e to z, while ë lies outside it. A person may read the notation as “the alphabet,” but the engine sees a specific range between two characters.
In Unicode, the code points for ë and Ë really do sit outside those continuous letter sequences. Range behavior can also depend on collation rules in different environments. In our sandbox, the rule is simple: add ë explicitly.
For lowercase letters, use [a-zëüó]; for uppercase, [A-ZËÜÓ]. If you need both cases, combine them in one character class: [A-Za-zëüóËÜÓ].
If the task is more specific and you need only two versions of the name, narrow the pattern instead. Zo[eë] reads as: Z, o, one e or ë, then e, e. It matches both Zoe and Zoë without changing the other positions.
[A-Za-z] ends at “z”; ë must be added to the character class explicitly.Add “ë” explicitly: [a-zëüó] for lowercase letters, [A-ZËÜÓ] for uppercase letters, and [A-Za-zëüóËÜÓ] for both cases. Each of these character classes chooses one character.
If only the variants “Zoë” and “Zoe” are allowed, Zo[eë] is more precise: only one position varies. In the export, contact 3 is stored as Zoë Miller.
The rules change a little inside square brackets
In the previous lesson, a dot was a metacharacter: you had to distinguish a dot from the command meaning “any character.” Inside a character class, the rules are simpler. [.] chooses one dot, and [.,] chooses one dot or one comma.
Take the string $5,990.00. [.,] finds the comma in it: $5,990.00. There is no dot in this string. In mail.com, the same pattern would find the dot.
A hyphen needs more care. Between the endpoints of a range, it has a special role, as in [0-9]. If you want the hyphen itself, one clear option is to put it at the end of the character class: [0-9-].
Walk through the string 45-67. 4 is in 0-9, and so is 5. Then comes the hyphen, which is explicitly allowed as the final item in the class. After that, 6 and 7 match. A global marker for [0-9-] highlights all five characters one by one.
But + isn't in this class. In the string +1, the pattern [0-9-] skips the plus and finds only 7.
You can also add a literal space to a character class. In [A-Za-zëüóËÜÓ ], there is a space just before the closing square bracket, so the class allows a Latin letter of either case or one regular space. That space is easy to miss by eye. In a real query, I'd check that exact spot especially carefully.
One character that isn't in the list
Phone numbers in the export use different formats: 13055550167, 45-67, tel. 1 (305) 555-0112. We need a quick way to spot all the formatting around the digits.
Put ^ immediately after the opening square bracket: [^0-9]. This character class chooses one character that isn't in the digit range.
Check 45-67. At 4, ask: “Is this character outside 0-9?” No. The answer is also no for 5. At the hyphen, it's yes. 6 and 7 don't match either. We get 45-67.
In the string 13055550167, there are no matches: every character is in 0-9.
In +1, the first match is +. The digit 7 doesn't match. The same rule also finds spaces, parentheses, and letters if they appear in the string.
Two forms of negation are easy to confuse here. phone !~ '[0-9]' checks whether the entire string contains no digits at all. phone ~ '[^0-9]' checks a different condition: whether there is at least one character that isn't a digit.
For 45-67, the first check is false because the string contains digits. The second is true because of the hyphen. For 13055550167, both checks are false: digits are present, and there are no nondigit characters.
QUERY:
^has two jobs. Immediately after[it negates the character class; outside square brackets it means the start of the string. We'll get to that in Chapter 3.
The query below removes every match for [^0-9]. For now, use it to compare the original phone number with what remains. We'll cover replacement itself in detail later.
One more short check. For each string, [^0-9] looks for at least one nondigit character.
123 — you can answer this one immediately.
12-3 — there is one symbol among the digits.
The empty string '' is more interesting. A character class must always choose one character, and there is nothing to choose in an empty string.
Work out all three cases in your head first, then run the query.
Short names for common classes
[0-9] isn't long to type, but digits, word characters, and whitespace appear in regexes all the time. These common classes have shorthand forms.
\d chooses one digit. In the phone numbers in our sandbox, it finds the same digits we just found with [0-9].
\w chooses one character from the “word” class: a letter, a digit, or _. In our environment, accented letters belong to this class too, including ë.
\s chooses one whitespace character. A regular space matches, but it isn't the only possibility: a tab, for example, belongs to this class too.
Break down KM-\d. K occupies the first position, M the second, the hyphen the third, and \d the fourth, where it requires one digit. On KM-2024, the match is KM-2024, just as with KM-[0-9].
Now look at \w. The string petrov_88 consists entirely of characters from this class: Latin letters, an underscore, and digits. A hyphen isn't included. In the surname Reed-Cole, the letters match \w, while - does not.
The letter ë also matches \w in our sandbox. This differs from [A-Za-z], where we had to add it manually.
These classes also have uppercase counterparts. \D chooses one nondigit character, \W chooses one character outside \w, and \S chooses one non-whitespace character.
Check _: it belongs to \w, so it doesn't belong to \W. For -, the opposite is true: \w is false and \W is true. For a regular space, \s is true and \S is false.
A backslash together with the next letter forms a command, and an unknown pair such as \q produces an error. Don't add a backslash “just in case”: the combination may already have a meaning in this regex .
The long form of the same class
In PostgreSQL documentation and other people's SQL, you'll see [[:digit:]]. The outer square brackets define a character class, while [:digit:] inside them names the predefined digit class. In PostgreSQL, \d and [[:digit:]] are equivalent. The same is true for \s and [[:space:]].
This notation comes from the POSIX family of standards. For example, [[:alpha:]] means letters. Its contents differ from \w: digits and underscore aren't part of alpha.
Letter classes have one more detail to keep in mind: their behavior depends on the database locale. The course runs in en_US.utf8, where the classes we use recognize accented letters. In the C locale, those letters aren't included in such classes. If you move a regex to another environment, run a short query with ë, _, a digit, and a hyphen instead of guessing what the class name includes.
Make the invisible visible
Contact 2 looks like a tidy “Petrov Sergey,” but six spaces are hidden around the words. On the page, they collapse together and disappear from view; the cell below will reveal each one.
\s chooses a whitespace character, so it's useful for checking strings like these. In the query below, each match is replaced with a dot.
For Anna Rivera, the result is simple: there is one space between the last name and first name, so one dot appears.
Petrov has two spaces at the beginning, three more between the words, and one after the name. So we expect two markers at the start, three in the middle, and one at the end.
Contact 16, Irene Reed-Cole, helps keep hyphens and spaces separate. The hyphen inside the surname doesn't belong to \s, so the only match here is the space before the first name.
Try to picture the output for all three contacts before running the query. In Petrov's row, pay particular attention to the beginning and end, where extra spaces are easiest to miss.
[cat] in the word “cat”?ë and Ë as foreign characters. Add both letters to the allowed class without removing the negation. Other foreign letters and a hyphen must still send the string to the list.Common mistakes
[cat] instead of cat
String: cat.
Expectation: the marker highlights the whole word.
In reality, [cat] chooses one letter from the list, so a global search gives cat.
A short three-character string exposes the mistake immediately. If you need three consecutive letters, write cat. Add square brackets only at a position where there is a choice, for example [cC]at.
Treating [A-Za-z] as the complete alphabet
String: Zoë.
Expectation: all lowercase letters fall inside the range.
But ë remains outside. If you replace matches for [A-Za-z] with dots, that letter stays visible among the replacements.
For lowercase letters in our sandbox, write [a-zëüó]; for both cases, use [A-Za-zëüóËÜÓ]. On another database, I wouldn't rely on memory: I'd run a short test with the characters I need and inspect the result.
Thinking a character class takes several characters
String: KM-2025-000311.
Expectation: KM-[0-9] highlights the entire numeric tail after KM-.
In reality, the pattern ends after the first digit: KM-2025-000311. [0-9] occupies one position. Repetition comes in the next chapter.
Confusing !~ with [^…]
String: 45-67.
Expectation with phone !~ '[0-9]': the string appears in the result because it contains a hyphen.
No. !~ requires there to be no matches for [0-9] at all, but the string contains digits. If you need to know whether there is at least one nondigit character, search for [^0-9].
To see the difference, use three short strings: 123, 12-3, and the empty string. They make the distinction clear without extra text around them.
Treating _ as an ordinary separator for \w
String: petrov_88.
Expectation: underscore falls outside the word class, just like a hyphen.
But _ belongs to \w, so \W won't find it. A hyphen -, by contrast, matches \W.
If a field rule specifically says “letters,” don't automatically replace it with \w: that class also includes digits and _.
How to build a character class for your own data
Suppose a new export arrives tomorrow. The code column allows Latin letters, digits, and hyphens. I wouldn't start with one large regex. First, I'd take one or two real strings and decide which characters are allowed in a single position.
For a Latin letter or digit, [a-zA-Z0-9] works. If a hyphen is allowed too, add it at the end: [a-zA-Z0-9-]. Then test _, a space, the letter ë, and a hyphen separately. Four small examples quickly show exactly what the pattern allows.
If the task is reversed and you need to find unwanted characters, put ^ immediately after the opening square bracket: [^a-zA-Z0-9-]. Then a space and _ become matches, while letters, digits, and a hyphen do not.
Use the same kind of check with shorthand classes. Before replacing a long character class with \w, check whether underscore is actually allowed by the field's rules. Before using \s, decide whether you need a regular space or any whitespace character. A regex knows only the condition you wrote; it doesn't know what the column means.
Key takeaways
- A character class chooses one character:
[cC]atfinds “cat” and “Cat,” while[cat]chooses one of three letters. - A range replaces a long list:
[0-9],[a-z]. In our sandbox, explicitly addëandËfor the accented letters used here:[A-Za-zëüóËÜÓ]. ^immediately after[negates the character class:[^0-9]finds one nondigit character. The!~operator checks a different condition.- Inside a character class, you can list punctuation marks.
[.,]finds a dot or comma, and[0-9-]finds a digit or hyphen. \d,\w, and\schoose a digit, a word-class character, and a whitespace character.\D,\W, and\Sdo the opposite.- In PostgreSQL,
\dis equivalent to[[:digit:]]. The behavior of letter classes depends on the locale, so it's best to test the characters you need with a short query.
Alyona no longer ends up on the “suspicious” list because of the letter ë. On the neighboring screen, KM-2 is still glowing: the character class selected the right digit, but only one. In the next chapter, we'll add repetition and reach the rest of the code.
SELECT ticket_id, regexp_replace(body, '[cC]at' , '⟦\&⟧' , 'g') AS marked
FROM tickets
WHERE body ~ '[cC]at'
ORDER BY ticket_id;