liveBook · Manning

Character class

As explained in The Quick Python Book, Fourth Edition

A character class is a regular-expression construct that matches one character from a specified set or range.

A character class matches one character chosen from a set. Write the choices between square brackets: `[hH]ello` matches `hello` or `Hello` because `[hH]` matches either form of the first letter. section 16.2

Inside the brackets, choices can be individual characters or ranges:

  • `[a-z]` matches one lowercase letter; `[0-9A-Z]` matches one digit or uppercase letter. section 16.2
  • Put a literal hyphen first so it is not read as a range: `[-012]` matches `-`, `0`, `1`, or `2`. section 16.2

Matching name characters

`[-a-zA-Z]` matches one hyphen or letter. Add `+` to match one or more such characters: `[-a-zA-Z]+` can match `McDonald` or `Perkin-Elmer`. It can also match `---`, so this pattern alone does not establish that a match is a valid name. section 16.4

Character classes can be combined with other regex constructs. In a contact-record pattern, `[-a-zA-Z]+` supplies each name component, while groups and `?` handle an optional middle name or area code. Outside a character class, the hyphens separating phone-number digits are ordinary hyphens. section 16.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines single-character matching, ranges, and literal-hyphen placement, then applies repetition; leaves broader regex subtleties to Python’s documentation.
Examples
Uses `[hH]ello`, letter and digit ranges, and hyphenated names in a name-and-phone-number pattern.
What it assumes
Assumes basic Python and regex-pattern use while defining what square brackets and ranges mean.
What you can do after
Apply it via Python `re` to choose permitted characters in patterns while recognizing that a broad class can match unwanted strings.
How it connects
Connects character classes to alternation, repetition, grouping, optional matches, and digit matching.

Also explained in

Compare how 9 books explain character class →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.