Sub topic 7
Regular expressions and the languages they denote
This chapter assumes you know alphabets, strings, and languages, plus the operations of union, concatenation, and Kleene star on languages. It also assumes you have seen DFAs and NFAs. The conversions between regular expressions and automata come in the next two chapters. Here the goal is to read a regular expression precisely, write one for a described language, and compare two expressions.
The formal definition
A regular expression (regex) over an alphabet Σ is built recursively. Each expression r denotes a language L(r).
| Expression | Language L(r) | Notes | Column |
|---|---|---|---|
| ∅ | the empty set {} | matches no string | |
| ε | {ε} | matches only the empty string | |
| a, for a in Σ | {a} | a single symbol | |
| r + s (or r\ | s) | L(r) ∪ L(s) | union |
| r s | L(r)L(s) | concatenation: every string of L(r) followed by one of L(s) | |
| r* | L(r)* | zero or more strings from L(r), joined | |
| (r) | L(r) | grouping only |
A language is regular exactly when some regular expression denotes it. Every regular expression is a finite description, but the language it denotes is usually infinite.
Note that ∅ and ε are different. L(∅) has no strings. L(ε) has one string, the empty one. This difference drives several identities below.
Precedence and parsing
Operators bind in this order, tightest first:
- Star (
*) - Concatenation
- Union
So ab*|c means (a(b*))|c. It does not mean (ab)*|c. Parentheses override the order.
The language is {c, a, ab, abb, abbb, ...}.
Reading an expression as a language
Work from the inside out. For (a|b)*abb:
a|bdenotes {a, b}.(a|b)*denotes every string over {a, b}, including ε.- Concatenating
abbgives every string over {a, b} that ends inabb.
This is the same language as the NFA in the earlier chapters. You can check a regular expression by listing its short strings:
import re
from itertools import product
def language_up_to(pattern, alphabet, max_len):
rx = re.compile(pattern)
words = []
for n in range(max_len + 1):
for tup in product(alphabet, repeat=n):
w = "".join(tup)
if rx.fullmatch(w):
words.append(w)
return words
print(language_up_to(r"(a|b)*abb", "ab", 4))
# ['abb', 'aabb', 'babb']fullmatch is the right call here. It requires the whole string to match, which is how a regular expression denotes a language. Functions like re.search ask a different question: whether some substring matches.
Writing expressions for common languages
Most GATE questions give you a description and ask for an expression, or the reverse. These patterns cover many cases. Assume Σ = {a, b}.
| Language | Expression | Column | Column | Column | Column | Column |
|---|---|---|---|---|---|---|
| All strings | `(a\ | b)*` | ||||
| Ends with `ab` | `(a\ | b)*ab` | ||||
| Contains `ab` as a substring | `(a\ | b)*ab(a\ | b)*` | |||
| Starts and ends with the same symbol, length ≥ 1 | `a(a\ | b)*a \ | b(a\ | b)*b \ | a \ | b` |
| Even number of `a`s | `b*(ab*ab*)*` | |||||
| At least one `a` | `b*a(a\ | b)*` | ||||
| Length divisible by 3 | `((a\ | b)(a\ | b)(a\ | b))*` | ||
| Third symbol from the end is `a` | `(a\ | b)*a(a\ | b)(a\ | b)` | ||
| No two consecutive `a`s | `(b\ | ab)*(a\ | ε)` |
Look at the "even number of a's" row. The expression b*(ab*ab*)* works because each block ab*ab* contains exactly two as, and the leading b* handles the case of zero. A common first attempt, (b*ab*a)*b*, is also correct. Two different expressions can denote the same language, so checking an answer means comparing languages, not text.
The "third from the end" row is worth remembering. Its smallest DFA needs 2³ = 8 states, but the expression stays short. This is the usual example of an expression being far more compact than the equivalent DFA.
Algebraic identities
Equivalence of expressions is a common question type. These identities hold for all expressions r, s, t:
- r + s = s + r, but rs ≠ sr in general.
- r(s + t) = rs + rt, and (r + s)t = rt + st.
- r∅ = ∅r = ∅
- rε = εr = r
- r + ∅ = r
- ∅ = ε = ε
- r r = r, and (r) = r
- r r = r r = r⁺ (one or more), and r = ε + r r
- (r + s) = (r s) = (r + s)*
The last line is the one most often tested. A union inside a star can be rewritten using a star of a concatenation. The shortcut (rs)* = r*s* is false. With r = a and s = b, the left side contains abab, but the right side only has strings of the form a…ab…b.
import re
from itertools import product
def same_up_to(p1, p2, alphabet, n):
r1, r2 = re.compile(p1), re.compile(p2)
for k in range(n + 1):
for tup in product(alphabet, repeat=k):
w = "".join(tup)
if bool(r1.fullmatch(w)) != bool(r2.fullmatch(w)):
return w # a counterexample string
return None # no difference found
print(same_up_to(r"(a|b)*", r"(a*b*)*", "ab", 6)) # None
print(same_up_to(r"(ab)*", r"a*b*", "ab", 6)) # a counterexample, e.g. 'aab'A search up to a length bound can only refute equivalence. It cannot prove it. Proving equivalence needs the identities above or a comparison of minimal DFAs.
Theory versus practical regex libraries
Libraries such as Python's re use a different syntax and extra features. Keep the two separate when answering exam questions.
- Union symbol. GATE textbooks often write
a + b. Python writesa|b. In Python,a+means "one or morea". - ∅. Python has no direct symbol for the empty language. The pattern
(?!)never matches, and the empty pattern matches only ε. - Extra power. Backreferences such as
(a*)b\1match the language {aⁿbaⁿ}, which is not regular. Such engines go beyond regular expressions in the theoretical sense. - Unanchored matching.
searchandmatchtest prefixes or substrings. Usefullmatchfor language membership.
Common errors
- Confusing ε with ∅.
r∅is ∅, butrεisr. Also∅*is {ε}, not ∅. - Missing parentheses.
ab*and(ab)*are different languages. So area|bcand(a|b)c. - Distributing star over concatenation.
(ab)* ≠ a*b*, as shown above. - Forgetting the empty string. In "no two consecutive a's",
(b|ab)*misses strings that end ina, so the final(a|ε)is needed. - Describing the language loosely. "Strings with an even number of
as" must include strings with zeroas.b*is in the language.
Exercise
Simplify (a + b)a(a + b) + b*. Which strings over {a, b} does it fail to match, if any?
Show answer
The first part matches every string that contains at least one a. The second part, b, matches the strings with no a, including ε. Together they cover every string over {a, b}. The expression is equivalent to (a + b), so it fails to match nothing.
Exercise
Is (ab) equal to ε + (a + b)*b? Give a short justification.
Show answer
Yes. Every string in (ab) is either ε or a concatenation of blocks of the form ab, so it is nonempty and ends in b. Conversely, any string ending in b can be split after each b into blocks ab. So the language is ε plus all strings over {a, b} that end in b, which is ε + (a + b)*b.
Exercise
Write a regular expression for binary strings over {0, 1} that contain exactly two 1s.
Show answer
01010. The two 1s are fixed, and each 0 allows any number of 0s before, between, and after them.