Consider the following non-deterministic finite automaton (NFA):
From formal language theory, we know that NFAs are equivalent to regular expressions, in the sense that for every NFA there is a regular expression that recognizes the same set of strings as the NFA. So, what is an equivalent regular expression for the NFA above?
In this post, I’d like to share a rather peculiar method to answer such questions by solving a system of linear equations over regular expressions1. Then, in order to justify this method rigorously, I’ll discuss two different approaches to put an algebraic structure on regular expressions—namely, Kleene algebras and non-commutative power series.
A suspicious question
To the question, let be a regular expression that matches strings that end in state when you run them through the automaton, and similarly let be a regular expression that matches strings ending in state . Although we don’t know what and are yet—if we did, we’d be done!—we can write down some constraints that they ought to satisfy. For instance, from the NFA diagram, the only way to get to state is if we haven’t seen any characters yet (an empty string), or if we were previously in state and saw the character . In other words, the regular expression should match either the empty string, or followed by the character .
Let’s now agree on two conventions for writing regular expressions: instead of using | to denote alternation as in , we will instead write , and additionally we’ll use to denote the regular expression matching the empty string. We’ll also agree that two regular expressions are equal if they match the same set of strings. Using these strange conventions, we get
which says that matches either the empty string, or followed by the character , as required. Similarly, for , we have the equation
We now throw caution to the wind completely and attempt to solve these equations algebraically, ignoring that we haven’t the faintest clue what manipulations on these “regular expression equations” are legal or what laws they obey, if any.
By manipulating equation (2), we get
Everyone and their mother knows that is just the sum of the infinite geometric series . Alas, we can’t have a regular expression of infinite length, but recalling that means alternation, the expression seems like it matches all the strings that are the character repeated. But that’s just the regular expression ! So:
Now substitute (3) into (1) to get . By applying our questionable geometric series trick again,
Substituting into (3) yields
and since is the only accepting state of the automaton, this regexp should match exactly the strings that are accepted by the NFA. And it truly does! This is the right answer to the original problem (!)
What the hell just happened?
Somewhat surprisingly, it turns out that this method does work in general! However, to understand what’s going on beneath the surface, we clearly first need to put some kind of algebraic structure on regular expressions that allows us to manipulate them formally. The goal of the rest of this post is to build up to two sensible algebraic interpretations of regular expressions.
Regular expressions revisited
To start, we should clarify what we mean by a regular expression: only basic features such as sequencing, alternation, and repetition () are permitted; fancy stuff like capturing groups, backreferences, and the like are all out of scope. Formally:
Definition (regular expression). A regular expression (regexp) is a recursive datatype given by one of the following cases:
- , matching the empty string
- a literal symbol , where is a fixed alphabet of valid symbols
- a sequence of two smaller regexps ; often we will omit the symbol and just juxtapose the regexps
- an alternation
- or a repetition .
(There’s in fact one more case, which we’ll get to later—in particular there is also such as a thing as ; see the first paragraph of the next section.)
We declare two regexps to be equal when they match the same set of strings. Formally, we define recursively a function that returns the set of strings that matches: , , etc. (What should the definition for be?2) Two regexps are then equal if .
As you have probably inferred, the object and the operations , behave somewhat like their real number counterparts. Here’s a non-exhaustive list of nice properties:
- addition is commutative: , since both match either or .
- is the identity with respect to multiplication: , since the left side means “match , then match ”, and matches the empty string.
- multiplication distributes over a sum: , since the left side means “match , then either or , which is the same as matching either or ”.
There are some oddities, of course. For instance:
- everything is idempotent with respect to : we have for all regexps .
- we do not have multiplicative inverses in general.3
- multiplication is not commutative: in general , since means to match followed by and the order matters.
Rings, semirings, and Kleene algebras
Perhaps you suspect at this point that the set of regular expressions forms a (non-commutative) ring. One obvious issue is that we don’t have an identity for addition; note that is not neutral with respect to addition, since matches both the empty string and , not just . This issue is easily remedied by adding a new object that matches no strings at all to the definition of regular expression. One can check that is indeed neutral with respect to addition and possesses various properties that something called zero ought to.
Unfortunately, even with the regular expressions do not have a ring structure for entirely trivial reasons. Indeed, additive inverses do not exist in general: given a regular expression , what is ? (One might be tempted to define it as the regular expression matching the complement of the language matched by , but unfortunately this does not play well with our existing definitions.4)
Thus is not a ring. However, one can actually check that the lack of additive inverses is the sole obstruction to being a ring. There is a name for structures that are almost rings but lack only additive inverses: semirings.
Definition (semiring). A semiring satisfies all the ring axioms, except that additive inverses need not exist.
Proposition. The set of regular expressions equipped with alternation as addition and sequencing as multiplication forms a semiring.
Proof. All the proofs in this post are left as exercises, partly because I am lazy :-) and partly because I think that the definitions and statements of results are more important than the proofs.
But this does not explain everything. In particular, we have not said how the star operation fits into the algebraic structure. If you recall how we “solved” the equation by heuristically writing “” and then using a “geometric series expansion” to get , it seems that the star operation acts as a kind of pseudoinverse.
The notion of a Kleene algebra extends the notion of a semiring to include the operation.
Definition (Kleene algebra). A Kleene algebra is an idempotent semiring with a unary operation such that
- for all , we have and ,
- for all , if then , and if then ,
where means .
For intuition about the definition of , observe that generally we may interpret in a semiring as a kind of union operation, and so is equivalent to “including” . In the setting of regular expressions, we see that implies that matches all the strings that does (and potentially more).
Proposition. The set of regular expressions is a Kleene algebra.
In fact, regular expressions are the prototypical example of a Kleene algebra; that is, Kleene algebras were introduced to study regular expressions!
In any case, from the defining axioms of a Kleene algebra, we can deduce the following
Lemma (Arden’s lemma). In a Kleene algebra, is the least solution of with respect to .
which (under a mild technical condition) validates our original rule used to solve the system of regular expressions at the start of the post.
The end of the story?
Kleene algebras are a cromulent and classical interpretation of regular expressions. Yet, one element of the Kleene algebra viewpoint that I personally find unsatisfying is that we originally “derived” the rule by heuristically manipulating , then multiplying by the inverse of and using a geometric series expansion to get
From the viewpoint of Kleene algebras, even though the end result is justified by Arden’s lemma and can be understood as a kind of pseudoinverse, the intermediate steps are nothing more than a heuristic and cannot be justified formally.
One would be excused for dismissing the argument above as nothing more than wishful thinking that chances upon the right answer—but in fact we can make this argument fully rigorous in the right setting. In particular, by interpreting regular expressions as formal noncommutative power series or formal power series over words, the “inverse” of a regular expression exists in a larger ring. In the last section of this post I will outline this viewpoint and sketch nice proofs of existence and uniqueness of solutions.
Formal power series over words
The motivation for this section is as follows: if you squint at a regular expression such as , it looks uncannily like a power series in two variables and . In fact, I claim this intuition is perfectly valid, and moreover it lets us subtract and invert things formally! The only sublety is that we need to work with a slightly exotic type of noncommutative power series5. To this end, let’s properly define what we mean by a noncommutative power series, also known as a formal power series over words.
Some definitions
We build up to the notion of a formal noncommutative power series from more familiar definitions.
Definition (formal power series in one variable). Let be a ring. Then denotes the ring of formal power series in the indeterminate with coefficients in .
Definition (formal power series in multiple commuting variables). Let be a ring. Then denotes the ring of formal power series in commuting indeterminates with coefficients in .
By commuting indeterminates, we mean that we can freely interchange the order in a product: . This allows us to rewrite any product of indeterminates in the canonical form .
If we drop this condition, and instead adjoin non-commutative indeterminates, we naturally obtain the definition of formal noncommutative power series. We indicate noncommutativity by using angled brackets instead of square brackets: that is, in the indeterminates and commute, whereas in they do not.
Let’s think about what the power series living in look like. In particular, what form do individual terms take? In the commutative case each term had the form , which does not distinguish between (say) and . In the noncommutative case these terms are distinct, so we should instead think about terms having the form
where is a finite sequence of 1s and 2s. The term corresponds to , whereas corresponds to , which is a different sequence.
In this way, we see that the power series living in are naturally indexed by words (finite sequences) where each symbol is in , of the form . This leads us to the definition
Definition (formal power series on words). Let be a ring and be a finite alphabet of symbols. Then denotes the ring of formal noncommutative power series .
and as a special case
Definition (formal power series in multiple noncommuting variables). Let be a ring. Then denotes the ring of formal power series .
It took us a bit to arrive at the right definitions, but I hope that the scenic route we took above gives some intuition for why power series on words is a natural non-commutative generalization of regular power series.
Remark. We can also see as the set of functions assigning each word a value in . (Why is this equivalent?)
Regular expressions are just power series
As alluded to earlier, regular expressions map to noncommutative power series over words in a natural way: for instance, we can think of
as a noncommutative power series in indeterminates , , over , where the coefficient on is and the coefficient on is also . Note that the coefficients need not always be 0/1 in general: consider , which expands to . The coefficient on counts the number of ways for the regular expression to match : see . More generally, the coefficient on a word counts the number of distinct parse trees for (the number of different ‘ways’ for the regular expression to match ).
What is the analogue of the star operation in ? It seems that we’re a bit stuck now, but let’s try the most naive definition possible: define as shorthand for the infinite sum . The beauty is that this sum really does exist under some assumptions on !
Theorem. Let be a ring and suppose that has no constant term. Then is invertible and moreover its inverse is .
With this in hand, we can define the correspondence between regular expressions and formal power series formally.
Definition (power series interpretation of regexp). Let denote the semiring of regular expressions over . Recall that denotes the ring of formal power series on words over .
Define the power series interpretation of a regular expression , denoted , by
- whenever does not match the empty string.
Here is a partial function .
Theorem. Let be a regular expression and suppose exists. Then the coefficient on each word in counts the number of ways that matches .
Corollary. Let be a regular expression and suppose exists. Then the set of strings matched by is exactly the set of words with nonzero coefficient in the power series .
The condition does not match the empty string in guarantees that has no constant term and hence is invertible. Intuitively, when matches the empty string, we should not expect to have a well-defined power series interpretation since there are infinitely many ways for match the empty string, hence the constant term of must be , which is not in .
In the power series interpretation of regular expressions, the heuristic argument that we originally made has a completely rigorous interpretation in , since subtraction is well-defined and the geometric series expansion is valid whenever has no constant term!
Working in also permits us to prove that the system of linear equations arising from NFA to regexp conversion has a solution. Indeed, take a -free NFA with states , initial states and accepting states . Define a row vector by if and otherwise. Also define a matrix by
For instance, if the alphabet is and the NFA contains transitions and , then .
Each entry of is a nonempty sum of literal symbols (as there are no -transitions), so has no constant term. Writing , the equations produced by our method become the single matrix equation
We can then prove
Theorem (existence and uniqueness). Let and be as above. Then the system has a unique solution , given by
Moreover, the coefficient of a word in is the number of paths in the NFA that start in a state of , read , and end in . In particular, the words with nonzero coefficient in are exactly the words accepted by the NFA.
The above result is not entirely complete, in the sense that it only guarantees a solution in , which may not correspond to a valid regular expression. Indeed, since the interpretation of a regular expression is the power series in which the coefficient on each word records the number of ways for to match the word, no power series with negative coefficients corresponds to a regular expression. One might then hope that every power series with non-negative coefficients corresponds to a regular expression, but this is not true either.6
In other words, only certain power series in can be converted back into valid regular expressions. Let denote the subsemiring of power series corresponding to valid regular expressions. It turns out that one can prove that the Gaussian elimination-like process we used to solve the original example problem stays in , which fills the gap in the result.
Conclusion
There’s lots more interesting things to say on this topic, but for now I will leave this post here—I hope it was a fun introduction to some more mathematical aspects of regular expressions. The ideas here are all quite classic, so let me conclude with a brief chronology:
- Kleene invented regular expressions in 1951;
- Schützenberger made the connection between automata and noncommutative power series in 1961;
- Arden proved that has solution , also in 1961;
- Brzozowski popularized the linear system method to convert NFAs to regexps in his seminal 1964 paper on derivatives of regular expressions;
- and Kozen introduced the modern definition of Kleene algebra used in this post in 1991, though similar ideas were around earlier.
-
I first learnt this method from Dr. Christian Urban’s course on compilers and formal languages at KCL on exchange. ↩︎
-
After a bit of pondering one arrives at the definition , where denotes the concatenation of strings and . ↩︎
-
Consider the regexp matching the literal character . Then, if is a multiplicative inverse of , we must have
and in particular this set cannot equal : the displayed set is either empty, or contains one or more strings starting with character . ↩︎
-
Every regular expression is idempotent with respect to , since matching either or is the same as matching ; that is, . If additive inverses exist, adding then gives . But was arbitrary, so this says that the only regular expression is —no good! ↩︎
-
Or maybe noncommutative power series are a triviality to you. Who knows? ↩︎
-
Indeed, taking , suppose that the power series corresponds to a regular expression . The set of strings matched by must then be the set of words with nonzero coefficient in , so that matches the language —but this language is not regular. ↩︎