Sub topic 3
Specifying tokens with regular expressions
This chapter assumes you know what a token, lexeme and pattern are (the previous chapter) and have seen basic set notation and string concatenation. Here you learn the notation used to write token patterns precisely, and the mistakes that make a pattern accept the wrong lexemes.
Why regular expressions
A lexer needs a short, exact description of every token class. A regular expression defines a set of strings, called a language, built from a small number of operations. Each token class such as identifier, integer or comment is one regular language. That is why a finite automaton can recognize it. The next chapters turn these expressions into automata.
The three core operations
Over an alphabet Σ, a regular expression is built from these rules:
- ε matches only the empty string. A symbol
ain Σ matches only the string "a". - Union
r|smatches anythingrmatches or anythingsmatches. - Concatenation
rsmatches a string fromrfollowed by a string froms. - Kleene closure
r*matches zero or more strings fromr, joined together. It always includes the empty string.
Precedence from highest to lowest is closure, then concatenation, then union. All three are left associative. So a|bc* means a | (b(c*)), not (a|b)c* and not (a|bc)*. Missing parentheses are a frequent exam error.
Useful laws:
| Law | Meaning | Column | Column |
|---|---|---|---|
| `r\ | s = s\ | r` | union is commutative |
| `r(s\ | t) = rs\ | rt` | concatenation distributes over union |
| `εr = rε = r` | ε is the identity for concatenation | ||
| `r** = r*` | closing twice adds nothing | ||
| `r* = (r\ | ε)*` | extra ε changes nothing inside a closure |
Concatenation is not commutative: ab and ba are different languages.
Shorthand extensions
Practical tools add notation. None of it adds power, because each form rewrites into the three core operations.
| Shorthand | Rewrites to | Meaning | Column | Column | Column |
|---|---|---|---|---|---|
| `r+` | `rr*` | one or more | |||
| `r?` | `r\ | ε` | zero or one | ||
| `[a-z]` | `a\ | b\ | ...\ | z` | character class |
| `[^x]` | every symbol except x | complemented class |
Regular definitions
Large patterns are named and built in steps. A regular definition is a sequence d1 → r1, d2 → r2, and so on. Each ri may use only the alphabet and earlier names, so no name can refer to itself. For example:
digit -> [0-9]
digits -> digit+
frac -> . digits
exp -> (E|e)(+|-)? digits
number -> digits frac? exp?The rule against self-reference is what keeps the language regular. A name that referred to itself, as in a pattern for nested parentheses, would describe a context-free language that no finite automaton can recognize.
Typical token patterns
- Identifier:
letter_ (letter_ | digit)*, whereletter_includes the underscore. The first symbol cannot be a digit. - Integer without leading zeros:
0 | [1-9][0-9]*. - Relational operators:
<|<=|>|>=|==|!=. - Line comment:
// [^\n]*. - String literal:
" ([^"\\\n] | \\.)* ". The\\.alternative lets an escaped quote sit inside the string.
The following program checks several of these patterns. re.fullmatch requires the whole string to match, which mirrors the idea of a pattern defining a language.
import re
PATTERNS = {
"ID": r"[A-Za-z_][A-Za-z0-9_]*",
"INT": r"0|[1-9][0-9]*",
"FLOAT": r"(0|[1-9][0-9]*)\.[0-9]+([eE][+-]?[0-9]+)?",
"LINE_COMMENT": r"//[^\n]*",
}
ACCEPT = {
"ID": ["x", "_tmp1", "a9"],
"INT": ["0", "7", "120"],
"FLOAT": ["3.14", "0.5e-3", "10.0E2"],
"LINE_COMMENT": ["// note", "//"],
}
REJECT = {
"ID": ["9a", "a-b", ""],
"INT": ["007", "", "1.5"],
"FLOAT": ["3.", ".5", "1e5"],
"LINE_COMMENT": ["/ note", "// a\nb"],
}
for name, pattern in PATTERNS.items():
for s in ACCEPT[name]:
assert re.fullmatch(pattern, s), (name, s)
for s in REJECT[name]:
assert not re.fullmatch(pattern, s), (name, s)
print("all patterns behave as specified")Common errors
- Unescaped metacharacters. In
.or+as written in a pattern, the symbol means "any character" or "repeat". To match a literal dot or plus, escape it, as in\.. - Wrong precedence.
ab*repeats onlyb. Use(ab)*to repeat both. - Greedy
.*in comments. A block comment written as/\* .* \*/can match from the first/*to the last*/on a line or file, swallowing code between comments. The correct pattern excludes the closing sequence inside the body. This is a lexer matter. The lexer chapter covers it. - Overlapping classes. A keyword such as
ifalso matches the identifier pattern. The regular expressions alone cannot decide, so the lexer uses a priority rule, covered later. - Expecting nesting. Regular expressions cannot count, so they cannot match balanced parentheses or nested comments. Those need a grammar.
GATE-style reasoning
Questions usually ask one of three things: whether a string is in a language, which of several expressions describe the same language, or how many strings of a given length match. Work through them as follows.
- Rewrite shorthand into core operations and apply precedence.
- Test the shortest strings first, including ε.
- Look for a distinguishing string that one expression accepts and the other rejects.
For example, (a|b)* and (a*b*)* are equal, since both match every string over {a, b}. But a*b* is smaller: it rejects ba.
Exercise
Write a regular expression over {a, b} for all strings that end with "ab". Then say whether "ab" and "bab" match, and whether "aba" matches.
Show answer
(a|b)*ab. Both "ab" and "bab" match, because each is some prefix (ε or "b") followed by "ab". "aba" does not match, since it ends with "ba".
Exercise
Does the pattern [0-9]+\.?[0-9]* match "5."? Does it match ".5"? Explain using the rewrites of + and ?.
Show answer
"5." matches: [0-9]+ takes "5", \.? takes ".", and [0-9]* takes ε. ".5" does not match, because the pattern requires at least one digit before the optional dot.