XML technologies / Regular expressions / Features and dialects / A tour of the world of regular expressions / The origins of regular expressions
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The seeds of regular expressions were sown in the early 1940s by two neurophysiologists. Warren McCulloch and Walter Pitts developed models of how they believed the nervous system worked at the neuronal level. (Note: “A logical calculus of the ideas immanent in nervous activity,” first published in Bulletin of Math. Biophysics 5, 1943, reprinted in Embodiments of Mind, MIT Press, 1965. The paper starts with an interesting account of how nerve cells, or neurons, work—did you know nerve impulses travel at speeds between 1 and 150 m/s? Then it becomes almost entirely formulas, which are quite literally Greek to me.) Regular expressions became a reality a few years later when mathematician Stephen Kleene formulated an algebra for these models, calling them regular sets. He also devised a simple notation for them, which he called Regular Expressions, or regular expressions.
In the 1950s and 1960s, regular expressions became a popular subject in theoretical mathematics. Robert Constable published a good survey for mathematically inclined readers: Robert L. Constable, “The Role of Finite Automata in the Development of Modern Computing Theory,” in The Kleene Symposium, edited by Barwise, Keisler, and Kunen, North-Holland Publishing Company, 1980, pp. 61–83.
There are references to earlier work, but the first publication I found about using regular expressions with computers is Ken Thompson’s 1968 paper, Regular Expression Search Algorithm (Communications of the ACM, Vol. 11, No. 6, June 1968), describing a regex compiler that generated IBM 7094 code. This led to qed, an editor that became the basis for the Unix editor ed .
Surprisingly, the regexes in ed were less powerful than the earlier ones in qed, but they were the first used by a sizeable community rather than merely researched. ed had, and still has, a command to print lines matching a regex. The command “g/Regular Expression/p” meant Global Regular Expression Print. This ed command was so popular that a separate program was written for it, giving birth to grep , from which egrep —extended grep —later developed.
Metacharacters in grep
These early tools had very limited regexes, even compared with egrep. The metacharacter * was supported, but neither + nor ? was; the missing question mark was a particularly serious disadvantage. Grouping used \(...\); ordinary parentheses were literals. (Note: Historical detail: ed, and therefore grep, uses \(...\) rather than unescaped parentheses because Ken Thompson expected regexes to be used mainly with C programs, where literal parentheses would occur far more often than backreferences.) grep supported line anchors, but only in restricted form. A ^ at the start of a regex was a start-of-line metacharacter, as in egrep or Perl. Elsewhere it was an ordinary literal circumflex. Similarly, $ was the end-of-line metacharacter only as the regex’s last character. This made something like ˹end$|^start˼ impossible, but that hardly mattered since alternation was unsupported too!
How metacharacters interact also matters. Perhaps the most serious limitation of grep was that star could apply only to literals, character classes, and dot, not parenthesized groups. Thus, parentheses in grep served only to remember earlier matched text, not for grouping in general.
grep evolves
Although grep exists on many modern systems, I have used the past tense because I meant the original versions of grep, thirty or more years old. As development progresses, tools are often revised and extended; grep is no exception.
At AT&T Bell Labs, grep acquired features such as the \{min, max\} notation from the lex program. The -y option, intended to ignore case in early versions but never reliable, was fixed. Around the same time, Berkeley developers added word-boundary metacharacters and renamed the -y option to -i. Unfortunately, star and other quantifiers still could not apply to parenthesized subexpressions.
egrep evolves
Around this time, Alfred Aho, also at AT&T Bell Labs, wrote egrep, offering a much richer set of metacharacters, most introduced in Introduction to regular expressions. More importantly, he implemented them in a very different and generally better way. The different implementation methods are the focus of How regex engines work and Regex techniques in practice. The characters ˹+˼ and ˹?˼ were added, now applying to subexpressions too, which gave egrep much greater expressive power.
Alternation was added, and line anchors became full metacharacters usable anywhere in a regex. egrep still had serious problems: sometimes a match was found but not printed, and some popular options were missing. Nevertheless, it was much more useful.
New species emerge
At about the same time, tools such as awk, lex and sed evolved too, often in their own directions. Developers tried to transplant features between tools, sometimes unsuccessfully. For example, to add plus to the metacharacters of grep we cannot simply use +: too many scripts already use grep with a literal ›+‹. But ›\+‹ is not something a grep user commonly needs, so it can introduce “one or more” without forcing users to relearn existing syntax.
New features sometimes introduce bugs; sometimes they are removed again. Tools were poorly documented, and the subtleties defining each regex dialect were usually undocumented. Many new tools tried to imitate existing ones, almost inevitably creating another dialect.
Repeating such changes creates considerable confusion, especially when working with many or all tools at once. Note: as might someone writing a book on regexes—ask me, I know all about it!
POSIX: An attempt at standardization
POSIX, short for Portable Operating System Interface, is a standard intended to ensure program portability between operating systems. This ambitious standard also specifies regexes and many traditional tools using them, so it concerns us even though no tool covered here fully meets every part of it. POSIX tries to clear up years of disorder by distilling the many existing variants into exactly two types: Basic Regular Expressions, or BREs, and Extended Regular Expressions, or EREs. POSIX-compliant systems must support one of these dialects. The next table shows the metacharacters of both POSIX variants.
Table: POSIX regex variants.
Regex feature | BRE | ERE |
|---|---|---|
Dot, | ✓ | ✓ |
Any-number quantifier | * | * |
Quantifiers + and ? | + ? | |
Interval quantifier |
|
|
Grouping |
|
|
Quantifiers apply to parenthesized expressions | ✓ | ✓ |
Backreferences | \1 through \9 | |
Alternation | ✓ | |
One concept in the POSIX standards is a locale: settings that adapt a system to a particular environment’s linguistic and cultural conventions. Examples include dates, times, monetary amounts, and character interpretation in a chosen collation sequence. The goal is program internationalization. This is not specific to regexes, but affects them too. If my locale uses the Latin-1 character set (ISO-8859-1), characters such as Ä and ä are letters, with numeric values 196 and 228, and case-insensitive tools treat them as identical. They lie outside ASCII. Note: here and throughout, ASCII means the original, unextended, unmodified 7-bit set without umlauts or accented letters. Most programs would otherwise treat them as binary data.
˹\w˼ often abbreviates a word character, the same as ˹[a-zA-Z0-9]˼. POSIX does not require this, but allows it. When supported, ˹\w˼ matches all alphabetic characters, not just English letters.
Note, however, that using Unicode almost always makes locale handling unnecessary.
Henry Spencer’s regex package
Also in 1986, and perhaps more importantly, Henry Spencer released a C regex package. He made it freely available, an absolute novelty then, so anyone could embed it in a program. Every program using it—and there were and are many—automatically shared a consistent dialect, unless its author modified the package.
Perl evolves too
Around then, Larry Wall began developing what would become Perl. He had already written patch, which greatly simplified distributed software development, but Perl would achieve truly monumental success.
Larry released Perl 1 in December 1987. It succeeded immediately by combining useful practical features from many existing languages and tools. Perl was useful in the literal sense.
One important feature was regexes inherited from sed and awk , something new for a scripting language. Larry reused the implementation from his newsreader rn, itself derived from James Gosling’s Emacs. Note: Gosling later designed, among other things, his own language, Java, which has its own regex implementation since version 1.4. This dialect was good for its time but sparse by today’s standards: at most nine parenthesis pairs and nine alternatives with ˹|˼. Worse, alternatives could not be parenthesized. Case-insensitive matching was impossible, ˹\w˼ could not be used in character classes, and ˹\s˼, ˹\d˼ and the interval quantifier ˹{min, max}˼ were unknown.
Perl 2 was released in June 1988. Larry completely replaced the regex code with a greatly expanded version of Spencer’s implementation described above. Nine parenthesis pairs remained the limit, but at least ˹|˼ could now appear inside them. ˹\d˼ and ˹\s˼ appeared, and the class ˹\w˼ now included underscore, allowed in Perl identifiers then and now. These metacharacters could also appear in character classes. Their opposites, ˹\D˼, ˹\W˼, and ˹\S˼, however, could not be used in classes and failed entirely in some cases. More importantly, the new /i modifier allowed case-insensitive matching.
Perl 3 arrived over a year later, in October 1989. The /e modifier brought unforeseen possibilities for replacement text, and backreference bugs were fixed. The ˹{min, max}˼ interval quantifier appeared, though with teething problems. Worse, version 3’s regex engine sometimes mishandled 8-bit data, so non-ASCII data could not be trusted to work correctly.
Perl 4 appeared eighteen months later, in March 1991, and improved steadily over the next two years, until its last release in February 1993. Earlier bugs and some restrictions disappeared: ˹\D˼ and similar constructs now worked in classes, and practically unlimited parentheses were allowed. Regex performance improved, but the real breakthrough came in 1994.
Perl 5 was officially released in October 1994. Perl was thoroughly revised and extended, becoming a much better language in every respect. Regex internals were optimized, and new metacharacters appeared, such as ˹\G˼ for finer control of iterative or global matching (see Start of the next match or end of the previous match: \G), non-capturing parentheses (see Solution 5), lazy quantifiers (see Lazy quantifiers: *?, +?, ??, {min, max}?), lookahead (see Section on lookahead), and the /x modifier. A small piece of Perl history: during a long discussion of a large, complicated regex, Larry saw a post of mine spreading it over several lines solely for readability. He liked it and thought scripts should allow the same layout, so he implemented what is now called the /x modifier (see Section on the /x modifier).
Beyond their functionality, these extensions showed that regexes had grown into a programming language of their own, with room for further development.
The new non-capturing parentheses and lookahead needed syntax. Every kind of bracket— (...), [...], <...> or {...} —was already taken, so Larry devised the ›(?‹ notation now familiar in various forms. He chose it because earlier regex versions rejected it, ensuring that existing programs could not accidentally use this new opener. Allowing only certain things after ›(?‹ also left room for future expansion.
Later Perl versions became more reliable, better optimized, and richer in features. The first edition of this book played a small part: I researched and tested regex features and sent findings to Larry and the Perl Porters, showing where improvements were needed.
Later additions included lookbehind (see Section on lookbehind), atomic groups (see Atomic groups: (?>...)), and support for Unicode. Conditional constructs (see Conditional regexes: (? if then|else)) added if-then-else decisions, and embedding Perl code in regexes brought things full circle (see Crazy things with Perl’s regex extensions). This book covers Perl 5.8.8.
Bringing order to regex dialects
Perl’s improvements arrived just in time for the Web revolution. Its strength is text processing, which is exactly what generating Web pages involves, so Perl quickly became the programming language for Web development. Its popularity grew, and so did that of its regex dialect.
Other language developers noticed, and several more or less Perl-compatible regex implementations emerged, including Tcl, Python, Microsoft’s .NET languages, Ruby, PHP, C/C++, and several Java packages.
Another kind of standardization came from Philip Hazel’s PCRE library, released in 1997, the year this book’s first edition appeared. PCRE, Perl Compatible Regular Expressions, closely reproduces the syntax and semantics of Perl’s regex implementation. Developers integrated this high-quality library into many tools, giving them rich, reliable, already familiar regex capabilities. PCRE is used in PHP, Apache HTTPD 2, Exim, Postfix, and Nmap, for example.
Program versions used in this book
The table lists version numbers for some languages, libraries, and other tools in this book. Earlier versions usually have fewer features and more bugs; newer versions may support new features and introduce new bugs.
Table: Versions of programs mentioned in this book.
GNU awk 3.1 |
| Procmail 3.22 |
GNU egrep/grep 2.5.1 | .NET Framework 2.0 | Python 2.3.5 |
GNU Emacs 21.3.1 | PCRE 6.6 | Ruby 1.8.4 |
flex 2.5.31 | Perl 5.8.8 | GNU sed 4.0.7 |
MySQL 5.1 | PHP (the | Tcl 8.4 |
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln