Character Classes and Special Sequences in Regular Expressions

Character Classes and Special Sequences in Regular Expressions

A character class lets a regular expression match one character chosen from a set. The brackets describe alternatives for a single position, not a string of characters.

import re

pattern = re.compile(r"[aeiou]")
print(pattern.findall("small example"))

This finds each vowel separately. The pattern [cat] matches c, a, or t; it does not match the word cat. To match that word, write cat without brackets.

Classes are useful when a position can contain several acceptable characters. For example, a simple identifier rule might allow a letter or underscore first, followed by letters, digits, or underscores:

identifier = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")

Inside a class, most punctuation loses its usual regex meaning. A period in [.] matches a literal period, and a plus sign in [+] matches a literal plus sign. The hyphen is the main exception: it can mark a range, as in [A-Z]. Put a hyphen at the beginning or end of a class to match it literally, or escape it.

special = re.compile(r"[-+.]")
print(special.findall("a-b+c.d"))

A closing bracket can be included by escaping it, as in []]. A backslash inside a Python string may itself need escaping, so raw strings are a practical default for regex patterns: r"[]]" passes the backslash through to the regex engine.

Ranges make common sets easier to write

A range replaces a list of consecutive characters. In a class, [0-9] means any character from 0 through 9, so it is equivalent to [0123456789].

digits = re.compile(r"[0-9]+")
print(digits.findall("room 12, floor 3"))

Ranges can be combined with other choices. This class accepts an ASCII letter, a digit, or an underscore:

word_char = re.compile(r"[A-Za-z0-9_]")
print(word_char.findall("item_24"))

The endpoints determine the range, and their order matters. [A-Z] matches uppercase ASCII letters; [a-z] matches lowercase ASCII letters. A range does not mean “all characters that seem like letters” in every language. In Python, these ranges cover the code points between their endpoints, which is why explicit ASCII ranges are useful when a format requires ASCII.

Ranges work only inside character classes. Outside brackets, the hyphen is just a literal hyphen, as in 2024-06-15. Inside a class, placement can change its meaning: [a-f] is a range, while [-af] matches a hyphen, a, or f.

date = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
print(bool(date.fullmatch("2024-06-15")))

Do not assume a range expresses a useful category merely because its endpoints look related. For example, [A-z] includes several punctuation characters between uppercase and lowercase letters in the character table. Write [A-Za-z] when the intent is both sets of ASCII letters.

Negated classes match what is left out

A caret at the start of a character class reverses the choice: the class matches one character this is not listed. For example, [^0-9] matches any character other than an ASCII digit.

not_digit = re.compile(r"[^0-9]")
print(not_digit.findall("room 12"))

This returns the letters and the space, not the digits. Negation applies to one character at a time. The pattern [^0-9]+ matches a run of non-digits; it does not mean “a string containing no digits” unless the match is required to cover the whole string.

text = "room 12"
print(bool(re.fullmatch(r"[^0-9]+", text)))
print(bool(re.fullmatch(r"[^0-9]+", "room")))

The first check is false because the input contains digits. The second is true. Choosing fullmatch matters: with search, the same pattern would succeed on the letters at the start of room 12.

Negated classes are handy for describing delimiters. To read a field up to a comma, match characters other than a comma, then match the comma itself:

field = re.compile(r"[^,]*,")
print(field.findall("red,green,blue"))

The class stops at the first comma because a comma is not among the characters it accepts. If a newline should also stop the field, include it explicitly: [^,n]*. In Python, a negated class such as [^,] can match a newline; the dot’s newline behavior does not apply to character classes.

The caret negates a class only in its first position. Elsewhere it’s an ordinary character, so [a^b] matches a, ^, or b. To include a literal caret in a negated class, place it after the initial caret, as in [^a^], or escape it.

A negated class describes everything the class does not list, not just the likely characters in your data. For instance, [^"]* accepts spaces, tabs, and newlines as well as ordinary text. If the input has stricter rules, make those rules explicit in the pattern.

Special sequences give meaning to common patterns

Some characters stand for sets that occur often enough to deserve short names. In Python, d matches a digit, s matches whitespace, and w matches a word character. Their uppercase forms match the complement of each set: D, S, and W.

import re

pattern = re.compile(r"w+s+d+")
print(pattern.findall("room 12, level 3"))

Here w+ matches a run of word characters, s+ matches one or more whitespace characters, and d+ matches a run of digits. The result is room 12 and level 3.

In Python, these sets are Unicode-aware by default. So d matches Unicode decimal digits, not only the ASCII characters from 0 through 9. Likewise, w includes Unicode alphanumeric characters as well as underscore. If a format requires ASCII digits or letters, use explicit ranges or compile with re.ASCII.

unicode_digits = re.compile(r"d+")
ascii_digits = re.compile(r"d+", re.ASCII)

print(bool(unicode_digits.fullmatch("٣")))
print(bool(ascii_digits.fullmatch("٣")))

The first check succeeds because the Arabic-Indic character is a Unicode decimal digit; the second fails because ASCII mode narrows d to ASCII digits. Explicitly writing [0-9] also makes that requirement visible in the pattern.

s matches whitespace such as spaces, tabs, and newlines. A pattern like s* can therefore cross a line break, which may matter when matching structured text. If only an ordinary space is allowed, write a literal space or a class containing just that character.

whitespace = re.compile(r"firsts+second")
print(bool(whitespace.search("firstnsecond")))

spaces_only = re.compile(r"first +second")
print(bool(spaces_only.search("firstnsecond")))

These short forms can also appear inside character classes. For example, [w.-]+ matches a run of word characters, periods, or hyphens; the class combines the named set with literal choices.

filename = re.compile(r"[w.-]+")
print(filename.findall("report-final.txt"))

Boundaries and escapes make patterns more precise

A boundary matches a position, not a character. The sequence b matches where a word character meets a non-word character, or where a word character meets the start or end of the string. This makes it useful for finding a whole word rather than a substring.

import re

text = "cat scatter catapult"
print(re.findall(r"bcatb", text))

Only the standalone cat matches. In scatter and catapult, the letters are next to other word characters, so there is no word boundary around them. In Python, word characters follow the Unicode-aware definition used by w, unless ASCII mode is enabled.

The opposite assertion, B, matches a position that’s not a word boundary. It can help find a character inside a word without matching the same character at its edges.

pattern = re.compile(r"BcatB")
print(pattern.findall("cat scatter catapult"))

Anchors also match positions. ^ matches the start of a string, and $ matches its end, with a special allowance for a final newline. With the re.MULTILINE flag, they match the beginnings and ends of lines as well.

text = "firstnsecond"

print(bool(re.search(r"^second$", text)))
print(bool(re.search(r"^second$", text, re.MULTILINE)))

The first search fails because second is not at the start of the whole string. The second succeeds because multiline mode treats the position after the newline as a line start. For an exact whole-string check, fullmatch is often clearer than adding anchors yourself.

number = re.compile(r"[0-9]+")
print(bool(number.fullmatch("482")))
print(bool(number.fullmatch("482 items")))

To match punctuation that normally has a special meaning, escape it with a backslash. For example, an unescaped period matches any character except a newline; . matches a literal period. The same principle applies to characters such as +, ?, and parentheses when they’re meant literally.

version = re.compile(r"[0-9]+.[0-9]+")
print(bool(version.fullmatch("3.14")))
print(bool(version.fullmatch("3x14")))

Raw Python strings make these patterns easier to read because Python passes their backslashes to the regex engine. Without a raw string, a backslash may be interpreted first by Python, so the pattern for a literal period would usually be written "\." instead of r".".

Raw strings still have Python’s string-literal rules: a raw string cannot end with an odd number of backslashes, because the final backslash would escape its closing quote. For patterns that need a literal backslash, escape it for the regex engine and keep the Python string raw:

backslash = re.compile(r"\")
print(backslash.findall(r"abc"))

Inside a character class, escaping is different in some details. A period has no special meaning there, but a closing bracket or backslash may need escaping. When a pattern becomes hard to read, split the matching logic into named pieces or use a small sequence of simpler checks.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *