Sub topic 7
Regular Expressions and the Languages They Denote
Prerequisites and central idea
Assume you know sets, strings, alphabets, and basic finite automata. A regular expression is a compact description of a regular language, which is a set of strings accepted by some finite automaton.
Let \(\Sigma\) be an alphabet. For example, \(\Sigma = \{a,b\}\). A regular expression describes a language over \(\Sigma\). The meaning of an expression is determined recursively.
The three basic operations
For regular expressions \(R\) and \(S\):
- \(R \mid S\) means union. A string belongs if it belongs to \(R\) or \(S\).
- \(RS\) means concatenation. A string belongs if it can be split into \(x y\), where \(x\) belongs to \(R\) and \(y\) belongs to \(S\).
- \(R^*\) means Kleene star. A string belongs if it is a concatenation of zero or more strings from \(R\).
The expression \(\epsilon\) denotes the language containing only the empty string. The symbol \(\emptyset\) denotes the empty language.
For example:
| Expression | Meaning |
|---|---|
| \(a \mid b\) | either `a` or `b` |
| \(ab\) | exactly `ab` |
| \(a^*\) | zero or more `a` symbols |
| \((a \mid b)^*\) | every string over \(\{a,b\}\) |
The usual precedence is:
- Kleene star
- Concatenation
- Union
Thus, \(ab^ \mid c\) means \((a(b^)) \mid c\). Parentheses should be used when the intended grouping is not obvious.
Derived notation
Several common operators are abbreviations:
- \(R^+ = RR^*\), meaning one or more copies of \(R\).
- \(R? = (R \mid \epsilon)\), meaning zero or one copy.
- \(R^{m,n}\) is often used informally for between \(m\) and \(n\) copies, but this is not part of the original formal definition.
A regular expression describes whole strings, not arbitrary substrings. In programming libraries, use a full-string operation when testing language membership.
import re
pattern = re.compile(r"(a|b)*abb")
print(bool(pattern.fullmatch("aabb"))) # True
print(bool(pattern.fullmatch("abab"))) # FalseThe first string ends in abb, so it matches. The second does not.
Reasoning about a language
To write an expression, divide the required strings into structural parts. The language of strings over \(\{a,b\}\) ending in abb is
\[ (a \mid b)^*abb. \]
The prefix may contain any symbols. The final part must be exactly abb.
The expression
\[ a^ba^ \]
describes strings with exactly one b, because any number of a symbols may appear before and after it. It does not describe bba, which contains two b symbols.
Exercise
Write a regular expression over {a,b} for strings that begin with a and contain any number of later symbols.
Show answer
a(a|b)*