Sub topic 2
Specifying Tokens with Regular Expressions
This chapter assumes you know basic regular languages and finite automata. You will use regular expressions to describe the token classes recognized by a lexical analyzer.
Tokens and token patterns
A token is a category produced by the lexer, such as ID, NUM, or PLUS. A lexeme is the exact character sequence from the source that belongs to that token.
For example, in:
total + 42total is a lexeme with token type ID, + has token type PLUS, and 42 has token type NUM.
A pattern is a rule that describes all lexemes in a token class. Regular expressions are a compact notation for these patterns.
| Notation | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `a` | The character `a` | `a` | ||
| `r \ | s` | `r` or `s` | `+ \ | -` |
| `rs` | `r` followed by `s` | `ab` | ||
| `r*` | Zero or more repetitions | `[0-9]*` | ||
| `r+` | One or more repetitions | `[0-9]+` | ||
| `[abc]` | One character from the set | `[A-Za-z]` | ||
| `(r)` | Grouping | `([+-])` |
Regular expression operators have precedence. Repetition binds most tightly, concatenation comes next, and alternation binds least tightly. Use parentheses when the intended grouping is not obvious.
Writing token patterns
Suppose identifiers begin with a letter or underscore and continue with letters, digits, or underscores. A suitable pattern is:
[A-Za-z_][A-Za-z0-9_]*An integer pattern is:
[0-9]+Several token specifications can be combined into one regular expression by naming each alternative. The following program recognizes identifiers, integers, operators, and whitespace:
import re
TOKEN_SPEC = [
("NUM", r"[0-9]+"),
("ID", r"[A-Za-z_][A-Za-z0-9_]*"),
("OP", r"[+\-*/()=]"),
("WS", r"\s+"),
]
MASTER = re.compile(
"|".join(f"(?P<{name}>{pattern})" for name, pattern in TOKEN_SPEC)
)
text = "count = 12 + total"
for match in MASTER.finditer(text):
if match.lastgroup != "WS":
print(match.lastgroup, match.group())The named groups make the token type available through match.lastgroup. The raw strings, such as r"[0-9]+", prevent Python from treating backslashes as string escapes before the regular expression engine sees them.
Visualizing the specification
Exercise
Exercise
Which regular expression describes an identifier that starts with a letter and may contain letters or digits afterward?
Show answer
[A-Za-z][A-Za-z0-9]*