Updated 2016-02-02 02:00:49 by AMG

The regular expression notation was invented by Kleene in the 1950's for specifying a regular language. This page is about regular expressions in general, not necessarily Tcl regular Expressions in Tcl.

RegExplorer

## Description  edit

A regular expression uses a particular notation to describe a pattern that a string of characters might match.

Some algorithms are easier coded without regular expressions. Tcl's string command is versatile, and often simplifies problems many programmers hit with the RE hammer.

To begin with, here are some definitions:
atom
a grouping of 0 or more characters which are to be treated as one entity by subsequent metacharacters, etc. If more than one character is to be included in an atom, then some sort of grouping syntax is needed. This is by analogy with the physical meaning of atom: an indivisible building block that underlies all other structures. Each atom is an individual regular expression, and can also be composed into larger expressions.
bracket expression
also called a character class, is a set of characters enlosed in brackets. It matches any of the characters in the brackets. For example, [a-z] matches can be any lower case alphabetic character from a to z. [^a-z] matches any ASCII character except a lower case alphabetic character. The bracket expression can contain various ranges of characters.
branch
ABC|DEF matches either ABC or DEF.
escape
an escape is one of a small set of characters preceeded by \
metasyntax
a sequence of (?metachars) where metachars is one or more alphabetic characters affecting the rest of the regular expressions. [metasyntax is one place where a variety of examples would be useful!]
quantifier
A metacharacter appended to a regular expression atom to indicate the number of times that atom may exist.

A regular expression atom is made of either a literal character or a metacharacter.

A literal character is the simplest regular expression possible. For example, a is a one-character regular expression. It can be used to match a portion of any string which contains the letter a. Search for a pattern matching the regular expression a in the string abc, and you get a match. Search for a pattern matching the regular expression a in the string xyz and you do not get a match.

A metacharacter, also known as an interpreted character, is intepreted as some non-literal pattern. For instance, the metacharacter . means 'match any character'. Search for the regular expression . in any string one character or longer and you get a match.

Another metacharacter is the \ (backslash). which indicates that the next character should be treated literally, even if it would normally be a metacharacter. This comes in most helpfully when attempting to describe patterns containing metacharacters.

A regular expression looks like a summary of the various forms that the set of strings it describes may take. | usually delimits alternative branches of the expression. * (the Kleene star) indicates zero or more occurances of the previous character, and use parentheses to group sub-expressions. All of these contsructs appear in the following example:
`A((b|cc)a)*`

The following strings are from the infinite set of matches for this expression:
`A Aba Acca Ababa Abacca Accaba Accacca Abababa`

An important factor for the popularity of regular expressions is their linear-time complexity: when a given string is to be matched against a regular expression, it is possible to do it so that every character in the string is only looked at once. This is attained by compiling the regular expression into a [finite automaton] — potentially a big chunk of work, but one that only needs to be done once for each regular expression — and then running the automaton with the string as input.

Another important factor is that regular expressions can be used for efficiently searching through a large body of text. A direct implementation of the above would produce an algorithm for matching a string against a regular expression, but most RE implementations, including [regexp], play a few tricks internally that make them operate in search mode instead. In order to get matching behaviour (often useful with switch -regexp), one uses the anchors ^ and \$ to require that the particular position in the regular expression must correspond to the beginning and end of the string respectively (caveat: sometimes it is beginning and end of line instead; AREs have \A and \Z as alternatives).

Other common extensions to the regular expression syntax, which however doesn't make them any more powerful than the basic set described above, are:
One-or-more quantifier (+)
Similar to *, but excluding the case of no repetition. The RE “(re)+” is equivalent to “(re)(re)*” and “(re)*(re)”.
Optional quantifier (?)
Also called the zero-or-one quantifier. The RE “(re)?” is equivalent to “(re|)”.
Bracket expression ([chars])
Effectively a shorthand — e.g. [abcd] is equivalent to (a|b|c|d) — but often far more compact. Unicode character classes often include thousands of character, so enumerating all of them would be unfeasible.
Counted quantifiers ({n} or {m,n})
Exactly n occurrencies, or at least m and at most n occurrencies, respectively. Can as ? be reduced to combinations of parentheses and |, but requires repeating the core RE the quantifier is applied to at least n times.
AND
Boolean "and", like | is boolean "or". Uncommon in regexp engines, and not easily reduced to the fundamental operations, but nonetheless the intersection of two regular languages is again a regular language. The grammar_fa package uses & to denote this.
NOT
Boolean negation. Uncommon in regexp engines, and not easily reduced to the fundamental operations, but nonetheless the complement of a regular language is also a regular language. The grammar_fa package uses ! to denote this.
Reversal
Change the direction in which the string is being matched; this may be useful to implement searching backwards in a text editor. There is no common syntax for this, but by hand transforming a regular expression accordingly is typically straightforward.

A somewhat intriguing class of such extensions are the constraints, which only match the empty string but refuse to do so unless the material surrounding the position of this match satisfies some condition. Here we find:
The regular expression re must match the text that follows after this position. This is similar to AND, but different in that re1 and re2 in ((?=re1)re2) are not required to match the same characters; re1 can match a prefix of what re2 matches, or vice versa.
The regular expression re must not match the text that follows after this position.
Positive lookbehind ((?<=re))
The regular expression re must match the text that comes before this position. This is not available in AREs.
Negative lookbehind ((?<!re))
The regular expression re must not match the text that comes before this position. This is not available in AREs.
Beginning of word (\m), end of word (\M)
These are obvious combinations of lookhead and lookbehind constraints, where one checks e.g. that the next character is a word character and the previous character was not.
Beginning or end of word (\y), not beginning or end of word (\Y)
Slightly more (but only marginally so) complicated combinations of lookahead and lookbehind.
Beginning of line (^), end of line (\$)
Similar to beginning and end of word.

The Tcl regexp engine handles lookaheads by compiling and running the constraint RE separately; in this way it is a "hybrid" RE engine.

Another set of usual extensions to the syntax concern submatch extraction and greediness. These mainly become meaningful when regular expressions are used for searching, as there in that case often are several substrings that match a particular RE, and it matters what match is reported.
Non-greedy quantifiers
Conventionally one lets quantifiers default to being greedy (match as much as possible), and introduce non-greedy quantifiers (match as little as possible) as variants; usual syntax is that a greedy quantifier followed by a ? becomes the corresponding non-greedy quantifier. Implementation-wise, the algorithm for non-greedy searching is easier than that for greedy searching.
Noncapturing parentheses
Usual notation is (?:re). The same as ordinary parentheses for searching and matching purposes, but tells the RE engine that it doesn't have to keep track of what range of a match corresponds to this parenthesis. Again, it is more work to keep track of this than to ignore it, but tradition dictates that parentheses should default to being capturing.

Many "regular expression" engines also support extensions to the syntax which allow them to go beyond the realm of regular languages. This is most common in backtracking RE engines (such as PCRE and the Perl engine) which ignores the finite automaton theory and instead uses trial and error to find a match, but some have escaped into more general standards.
Back references (\n)
Matches the exact substring matched by the nth capturing parenthesis in the RE. This is labelled the Feature from the Black Lagoon in the sources for the Tcl regexp engine. The (only?) non-regular feature found in the regular expressions of the POSIX standard. Practical applications include parsing data where one can introduce custom separator strings.
To see the power of back references, one may observe that they can be used to recognise primes. ^(oo+?)\1+\$ will match a string of n o's if and only if n is a product ab for integers a,b ≥ 2; a is the length of submatch 1 and b is the number of times it is repeated.
Recursive match (\R) and subroutines
Behave as if a copy of the whole regular expression, or of some "named subexpression", occurred at this point when trying to match. Together with |, this is all one needs for a general context-free grammar [1] (although the syntax is typically hideous compared to the standard BNF notation for these), which conversely means any engine capable of these features have to be at least as slow (roughly time cubic in input size) as a context-free language parser when handling these, and quite likely far slower for the worst cases. The Tcl regexp engine does not have these features.

## How Regular Expression Features are Implemented using Finite Automata  edit

This is a partial list of tricks. It also assumes some familiarity with finite automata theory, such as knowing what distinguishes an NFA from a DFA, how one runs them, and how one can construct one from the other (all of which is standard material in relevant computer science courses).

### Search mode regexps

Given a match-mode regexp engine, as one would get from running a finite automaton over a string and inspect whether the end state is final, one can run a regular expression re in search mode on it by running .*(re).* in match mode.

[Also explain what one can do to find the match searched for, without going for a full-blown submatch-capable engine.]

### Submatch capturing

As usually defined, finite automata can only answer "yes" or "no", so there's no way to get submatch information out of them.

An extension of the formalism (keeping track of positions within the string corresponding to positions in the regexp, as well as the basic automaton state) can be found in NFAs with Tagged Transitions, their Conversion to Deterministic Automata and Application to Regular Expressions

### Boolean AND / language intersection

This is a classic trick.

Given one (ε-free) automaton A1 for matching the regular expression re1 and another (ε-free) automaton A2 for matching the regular expression re2, it is straightforward to construct an automaton A for re1 AND re2 as follows:

1. If the state set of A1 is S1 and the state set of A2 is S2, then the state set of A will be S1 × S2 (cartesian product of the two sets).
2. There is a transition from (u1,u2) to (v1,v2) labelled x in A if and only if there is a transition from u1 to v1 labelled x in A1 and a transition from u2 to v2 labelled x in A2.
3. A state (u,v) is final in A if and only if u is final in A1 and v is final in A2.
4. Similarly, a state (u,v) is initial in A if and only if u is initial in A1 and v is initial in A2.

What this means in practice is that running A is equivalent to running A1 and A2 simultaneously; each A state is a pair of an A1 state and an A2 state. A accepts a string only if both A1 and A2 would do so.

### Boolean NOT / language complementation

Assuming you've got a DFA for matching a regular language, this is very straightforward: negate the "final" status for every state. States that were previously accepting will then be non-accepting, and vice versa, so strings that were previously accepted will now be rejected (and vice versa).

The basic idea is the same as for boolean AND. First make an automaton for the main RE, then make so many copies of this that you can simultaneously keep track of the state visavi the man RE and the constraint RE, while adjusting the transitions suitably so that you run both in parallel; the projection onto either axis will however still be automata for the main and constraint respectively RE. Finally modify the sets of initial and final states appropriately for the wanted result.

Basically, the projection of the constraint onto the main RE "axis" would be an ε-transition, but it is not parallel to that axis. Rather, it will take you from being debt-free (having all instances of the constraint satisfied, and the string as a whole thus eligible for acceptance) to a debt of 1 match (preventing the string from being accepted), and in order to become free of this debt you will have to work the automaton until reaching a constraint-accepting state again (kind of like an old platform game, where one might fall down a chute into the underground and then painfully having to work one's way up to the surface again before being allowed to finish the game).

What makes this more complicated than the boolean AND is that several instances of the constraint may be relevant at the same time. Consider for example
`((?=(...)?a)[abc])*`

where each iteration of the outer parenthesis eats one letter, but the constraint is looking for an a up to four characters ahead. It seems the only way to manage that is to run all possibilities in parallel, which means the "constraint axis" of the composite automaton is labelled not by states of an automaton for matching the constraint RE, but by sets of such states (like in the subset construction — no wonder the Tcl engine prefers to go hybrid here)!

Also, that construction only takes care of one constraint at a time. In order to remove all constraints, it would be necessary to repeat it as many times as there are constraints in the expression! Luckily, constraint REs encountered in practice (such as those for beginning-of-word, look one character back and forth) tend to require only a very small number of states, so it is in fact feasible to use them, even with a pure automaton engine.

## Regular expression puzzles  edit

AMG: I found a couple regular expression puzzles online that are very good for practicing and improving your regular expression skills. Highly recommended. They're not written in Tcl, but I think creating Tcl versions would be a wonderful project.
Regex Crossword [2]
Fill in a rectangular or hexagonal grid to simultaneously satisfy all the regular expressions
Regex Golf [3]
Write a regular expression that matches everything in one set and nothing in another set

## Regular expression flavours  edit

[Old discussion, could do with refactoring.]

Okay then - feel free to add information here on the other RE flavors available in Tcl...

LES says that there no other RE flavors available in Tcl. Tcl only uses ARE. What I meant is that regular expressions may be construed as any one (or all) of its several variations, but Regular Expressions only discusses Tcl's ARE. I said that because this wiki discusses many things under several contexts, not necessarily that of Tcl, and I thought it would be good to note that, at least in this case, it is restricted to the context of Tcl. Anyone interested in a different or more ample discussion of Regular Expressions will have to look elsewhere. E.g. on PCRE.

Regular Expressions
describes Tcl's regular expressions (advanced regular expressions)
The Open Group Base Specifications Issue 7, Regular Expressions
AKA POSIX
regularexpressions.info
lots of general information, and a thorough tutorial with examples (CL: although its imprecisions exasperate). See the examples for an extensive listing of regulare expressions for various tasks.
Regular Language, Wikipedia
a formal definitions of "regular language".
BOOK Mastering Regular Expressions, by Jeffrey E. F. Friedl
considered almost the definitive tome on regular expressions, from the Unix grep(1) command to Tcl and beyond.
Regular Expressions - a brief history, by Staffan Nöteberg, 2013-01-30
Regular Expression Matching: History, Status, and Challenges, Philip Bille
Regular Expressions explained, Jan Borsodi, 2000-10-30
Five Habits for Successful Regular Expressions, Tony Stubblebine, 2003-08-21
Know your regular expressions, Michael Stutz, 2007-06-14
features a flexible RE generator
regexlib.com
a community maintained library of regular expressions