Jump to content

Regular expression

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by The-stickman (talk | contribs) at 10:07, 9 March 2007 (History: Added Philip Hazel link). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

In computing, a regular expression (abbreviated as regexp or regex, with plural forms regexps, regexes, or regexen) is a string that describes or matches a set of strings, according to certain syntax rules. Regular expressions are used by many text editors and utilities to search and manipulate bodies of text based on certain patterns. Many programming languages support regular expressions for string manipulation. For example, Perl and Tcl have a powerful regular expression engine built directly into their syntax. The set of utilities (including the editor ed and the filter grep) provided by Unix distributions were the first to popularize the concept of regular expressions.

Many modern computing systems provide wildcard characters in matching filenames from a file system. This is a core capability of many command-line shells and is known as globbing. Wildcards differ from regular expressions in that they can only express very restrictive forms of alternation.

Basic concepts

A regular expression, often called a pattern, is an expression that describes a set of strings. They are usually used to give a concise description of a set, without having to list all elements. For example, the set containing the three strings Handel, Händel, and Haendel can be described by the pattern "H(ä|ae?)ndel" (or alternatively, it is said that the pattern matches each of the three strings). In most formalisms, if there is any regex that matches a particular set then there is an infinite number of such expressions. Most formalisms provide the following operations to construct regular expressions.

alternation
A vertical bar separates alternatives. For example, "gray|grey", which could be shortened to the equivalent "gr(a|e)y", can match "gray" or "grey".
grouping
Parentheses are used to define the scope and precedence of the operators. For example, "gray|grey" and "gr(a|e)y" are different patterns, but they both describe the set containing gray and grey.
quantification
A quantifier after a character or group specifies how often that preceding expression is allowed to occur. The most common quantifiers are ?, *, and +:
?
The question mark indicates there is 0 or 1 of the previous expression. For example, "colou?r" matches both color and colour.
*
The asterisk indicates there are 0, 1 or any number of the previous expression. For example, "go*gle" matches ggle, gogle, google, gooogle, etc.
+
The plus sign indicates that there is at least 1 of the previous expression. For example, "go+gle" matches gogle, google, gooogle, etc. (but not ggle).

These constructions can be combined to form arbitrarily complex expressions, very much like one can construct arithmetical expressions from the numbers and the operations +, -, * and /.

So "H(ae?|ä)ndel" and "H(a|ae|ä)ndel" are valid patterns, and furthermore, they both match the same strings as the example from the beginning of the article.

The pattern "((great )*grand )?((fa|mo)ther)" matches any ancestor: father, mother, grand father, grand mother, great grand father, great grand mother, great great grand father, great great grand mother, great great great grand father, great great great grand mother and so on.

The precise syntax for regular expressions varies among tools and application areas; more detail is given in the Syntax section.

History

The origins of regular expressions lies in automata theory and formal language theory, both of which are part of theoretical computer science. These fields study models of computation (automata) and ways to describe and classify formal languages. The mathematician Stephen Kleene in the 1950s described these models using his mathematical notation called regular sets. Ken Thompson built this notation into the editor QED as a means to match patterns in text files. He later added this capability to the Unix editor ed, which eventually led to the popular search tool, grep's use of regular expressions ("grep" is a word derived from the command for regular expression searching in the ed editor: g/re/p where re stands for regular expression). Ever since that time, many variations of Thompson's original adaptation of regular expressions have been widely used in Unix and Unix-like utilities such as: expr, awk, Emacs, vi, lex, and Perl.

Perl and Tcl regular expressions were derived from regex written by Henry Spencer, though Perl later expanded on Spencer's regex library to add many new features.[1] Philip Hazel developed PCRE (Perl Compatible Regular Expressions) which attempts to closely mimic Perl's regular expression functionality, and is used by many modern tools such as PHP, ColdFusion, and Apache. Part of the effort in the design of Perl 6 is to improve Perl's regular expression integration, and to increase their scope and capabilities to allow the definition of parsing expression grammars.[2] The result is a mini-language called Perl 6 rules, which are used to define Perl 6 grammar as well as provide a tool to programmers in the language. These rules maintain all of the features of regular expressions, but also allow BNF-style definition of a recursive descent parser via sub-rules.

The use of regular expressions in structured information standards (for document and database modeling) was very important, started in the 1960s, and expanded in the 1980s, when industry standards like ISO SGML (precursored by ANSI "GCA 101-1983") consolidated. The kernel of the structure specification language standards are regular expressions. The more simple and evident use are in the DTD element group syntax.

Formal language theory

Regular expressions can be expressed in terms of formal language theory. Regular expressions consist of constants and operators that denote sets of strings and operations over these sets, respectively. Given a finite alphabet Σ the following constants are defined:

  • (empty set) ∅ denoting the set ∅
  • (empty string) ε denoting the set {ε}
  • (literal character) a in Σ denoting the set {a}

and the following operations:

  • (concatenation) RS denoting the set { αβ | α in R and β in S }. For example {"ab", "c"}{"d", "ef"} = {"abd", "abef", "cd", "cef"}.
  • (alternation) R|S denoting the set union of R and S.
  • (Kleene star) R* denoting the smallest superset of R that contains ε and is closed under string concatenation. This is the set of all strings that can be made by concatenating zero or more strings in R. For example, {"ab", "c"}* = {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", ... }.

The above constants and operators form a Kleene algebra.

Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.

To avoid brackets it is assumed that the Kleene star has the highest priority, then concatenation and then set union. If there is no ambiguity then brackets may be omitted. For example, (ab)c is written as abc and a|(b(c*)) can be written as a|bc*.

Examples:

  • a|b* denotes {ε, a, b, bb, bbb, ...}
  • (a|b)* denotes the set of all strings consisting of any number of a and b symbols, including the empty string
  • ab*(c|ε) denotes the set of strings starting with a, then zero or more bs and finally optionally a c.
  • (aa|ab(bb)*ba)*(b|ab(bb)*a)(a(bb)*a|(b|a(bb)*ba)(aa|ab(bb)*ba)*(b|ab(bb)*a))* denotes the set of all strings which contain an even number of as and an odd number of bs.

The formal definition of regular expressions is purposely parsimonious and avoids defining the redundant quantifiers ? and +, which can be expressed as follows: a+ = aa*, and a? = (ε|a). Sometimes the complement operator ~ is added; ~R denotes the set of all strings over Σ* that are not in R. The complement operator is redundant: it can always be expressed by only using the other operators (the process for computing such a representation is complex, and the result may be exponentially larger, but it is possible).

Regular expressions in this sense can express exactly the class of languages accepted by finite state automata: the regular languages. There is, however, a significant difference in compactness: some classes of regular languages can only be described by automata that grow exponentially in size, while the length of the required regular expressions only grow linearly. Regular expressions correspond to the type 3 grammars of the Chomsky hierarchy and may be used to describe a regular language. On the other hand, there is a simple mapping between regular expressions and nondeterministic finite automata (NFAs) that does not lead to such a blowup in size; for this reason NFAs are often used as alternative representations of regular expressions.

We can also study expressive power within the formalism. As the example shows, different regular expressions can express the same language: the formalism is redundant.

It is possible to write an algorithm which for two given regular expressions decides whether the described languages are essentially equal, reduces each expression to a minimal deterministic finite state automaton, and determines whether they are isomorphic (equivalent).

To what extent can this redundancy be eliminated? Can we find an interesting subset of regular expressions that is still fully expressive? Kleene star and set union are obviously required, but perhaps we can restrict their use. This turns out to be a surprisingly difficult problem. As simple as the regular expressions are, it turns out there is no method to systematically rewrite them to some normal form. They are not finitely axiomatizable. So we have to resort to other methods. This leads to the star height problem.

It is worth noting that many real-world "regular expression" engines implement features that cannot be expressed in the regular expression algebra; see below for more on this.

Syntax

Traditional Unix regular expressions

The "basic" Unix regular expression syntax is now defined as obsolete by POSIX, but is still widely used for the purposes of backwards compatibility. Most regular-expression-aware Unix utilities, such as grep and sed, use it by default while providing support for extended regular expressions with command line arguments (see below).

In the basic syntax, most characters are treated as literals — they match only themselves (i.e. "a" matches "a", "(bc" matches "(bc", etc). The exceptions are called metacharacters:

. Matches any single character. Into [ ] this character has its habitual meaning. For example, "a.cd" matches "abcd", "a..d" matches "abcd".
[ ] Matches a single character that is contained within the brackets. For example, [abc] matches "a", "b", or "c". [a-z] matches any lowercase letter. These can be mixed: [abcq-z] matches a, b, c, q, r, s, t, u, v, w, x, y, z, and so does [a-cq-z].

The '-' character should be literal only if it is the last or the first character within the brackets: [abc-] or [-abc]. To match an '[' or ']' character, the easiest way is to make sure the closing bracket is first in the enclosing square brackets: [][ab] matches ']', '[', 'a' or 'b'.

[^ ] Matches a single character that is not contained within the brackets. For example, [^abc] matches any character other than "a", "b", or "c". [^a-z] matches any single character that is not a lowercase letter. As above, these can be mixed.
^ Matches the start of the line (or any line, when applied in multiline mode)
$ Matches the end of the line (or any line, when applied in multiline mode)
( ) Defines a "marked subexpression". What the enclosed expression matched can be recalled later. See the next entry, \n. A "marked subexpression" is also a "block". This feature is not found in some instances of regex. In most Unix utilities (such as sed and vi) a backslash must precede the open and close parentheses.
\n Where n is a digit from 1 to 9; matches what the nth marked subexpression matched. This construct is theoretically irregular and has not been adopted in the extended regular expression syntax.
* A single character expression followed by "*" matches zero or more copies of the expression. For example, "ab*c" matches "ac", "abc", "abbbc" etc. "[xyz]*" matches "", "x", "y", "zx", "zyx", and so on.
  • \n*, where n is a digit from 1 to 9, matches zero or more iterations of what the nth marked subexpression matched. For example, "(a.)c\1*" matches "abcab" and "abcabab" but not "abcac".
  • An expression enclosed in "\(" and "\)" followed by "*" is deemed to be invalid. In some cases (e.g. /usr/bin/xpg4/grep of SunOS 5.8), it matches zero or more iterations of the string that the enclosed expression matches. In other cases (e.g. /usr/bin/grep of SunOS 5.8), it matches what the enclosed expression matches, followed by a literal "*".
{x,y} Match the last "block" at least x and not more than y times. For example, "a\{3,5}" matches "aaa", "aaaa" or "aaaaa". Note that this is not found in some instances of regex.

Note that particular implementations of regular expressions interpret backslash differently in front of some of the metacharacters. For example, egrep and Perl interpret unbackslashed parentheses and vertical bars as metacharacters, reserving the backslashed versions to mean the literal characters themselves. Old versions of grep did not support the alternation operator "|".

Examples:

".at" matches any three-character string like hat, cat or bat
"[hc]at" matches hat and cat
"[^b]at" matches all the matched strings from the regex ".at" except bat
"^[hc]at" matches hat and cat but only at the beginning of a line
"[hc]at$" matches hat and cat but only at the end of a line

Since many ranges of characters depends on the chosen locale setting (e.g., in some settings letters are organized as abc..yzABC..YZ while in some others as aAbBcC..yYzZ), the POSIX standard defines some classes or categories of characters as shown in the following table:

POSIX class similar to meaning
[:upper:] [A-Z] uppercase letters
[:lower:] [a-z] lowercase letters
[:alpha:] [A-Za-z] upper- and lowercase letters
[:alnum:] [A-Za-z0-9] digits, upper- and lowercase letters
[:digit:] [0-9] digits
[:xdigit:] [0-9A-Fa-f] hexadecimal digits
[:punct:] [.,!?:...] punctuation
[:blank:] [ \t] space and TAB characters only
[:space:] [ \t\n\r\f\v] blank (whitespace) characters
[:cntrl:] control characters
[:graph:] [^ \t\n\r\f\v] printed characters
[:print:] [^\t\n\r\f\v] printed characters and space

Example: [[:upper:]ab] should only match the uppercase letters and lowercase 'a' and 'b'.

It is generally agreed that [:print:] consists of [:graph:] plus the space character. However, in Perl regular expressions [:print:] matches [:graph:] union [:space:].

An additional non-POSIX class understood by some tools is [:word:], which is usually defined as [:alnum:] plus underscore. This reflects the fact that in many programming languages these are the characters that may be used in identifiers. The editor vim further distinguishes word and word-head classes (using the notation \w and \h) since in many programming languages the characters that can begin an identifier are not the same as those that can occur in other positions.

(For an ASCII chart color-coded to show the POSIX classes, see ASCII.)

Greedy expressions

Quantifiers in regular expressions match as much as they can; they are greedy (meaning they try to match the maximum available). This can be a significant problem. For example, someone wishing to find the first instance of an item in double-brackets in the text

Another whale explosion occurred on [[January 26]], [[2004]], in [[Tainan City]], [[Taiwan]].

would most likely use the pattern (\[\[.*\]\]), which seems correct (note that the square bracket is preceded by a back slash as it is to be interpreted as a literal character). However, this pattern will actually return [[January 26]], [[2004]], in [[Tainan City]], [[Taiwan]] instead of the expected [[January 26]]. This is because it will return everything between the first 2 left brackets from [[January 26]] and the last 2 right brackets from [[Taiwan]].

Though this problem can be avoided in a number of ways (e.g. by specifying the text that is not to be matched as in: (\[\[[^\]]*\]\])), modern regular expression tools allow a quantifier to be specified as non-greedy, by putting a question mark after the quantifier: (\[\[.*?\]\]). By matching non-greedily, the expression tries the minimal match first. Though in the previous example, minimal matching is being used to select one of many matching results, it can also improve performance of matches when maximal matching would require more backtracking.

In PHP programming, you can assert that all quantifiers in a regex are non-greedy, by adding a 'U' at the end of the regex (just after the finishing slash). For example, /\[\[.*\]\]/U

POSIX modern (extended) regular expressions

The more modern "extended" regular expressions can often be used with modern Unix utilities by including the command line flag "-E".

POSIX extended regular expressions are similar in syntax to the traditional Unix regular expressions, with some exceptions. The following metacharacters are added:

+ Match the last "block" one or more times - "ba+" matches "ba", "baa", "baaa" and so on
? Match the last "block" zero or one times - "ba?" matches "b" or "ba"
| The choice (or set union) operator: match either the expression before or the expression after the operator - "abc|def" matches "abc" or "def".

Also, backslashes are removed: \{...\} becomes {...} and \(...\) becomes (...). Examples:

"[hc]+at" matches with "hat", "cat", "hhat", "chat", "hcat", "ccchat" etc.
"[hc]?at" matches "hat", "cat" and "at"
"([cC]at)|([dD]og)" matches "cat", "Cat", "dog" and "Dog"

Since the characters '(', ')', '[', ']', '.', '*', '?', '+', '^' and '$' are used as special symbols they have to be escaped if they are meant literally. This is done by preceding them with '\' which therefore also has to be escaped this way if meant literally. Examples:

"a\.(\(|\))" matches with the string "a.)" or "a.("

Perl-compatible regular expressions (PCRE)

Perl has a richer and more predictable syntax than even the extended POSIX regexp. An example of its predictability is that \ always quotes a non-alphanumeric character. An example of something that is possible to specify with Perl but not POSIX is whether part of the match wanted to be greedy or not. For instance in the pattern /a.*b/, the .* will match as much as it can, while in the pattern /a.*?b/, .*? will match as little. So given the string "a bad dab", the first pattern will match the whole string, and the second will only match "a b".

For these reasons, many other utilities and applications have adopted syntaxes that look a lot like Perl's — for example, Java, Ruby, Python, PHP, exim, BBEdit, and Microsoft's .NET Framework all use regular expression syntax similar to Perl's. Not all "Perl-compatible" regular expression implementations are identical, and many implement only a subset of Perl's features. With the Perl 5.9.x (development track for Perl 5.10) this process has come full circle with Perl incorperating syntax extensions originally from Python, the .NET Framework, and Java.

Patterns for irregular languages

Many patterns provide an expressive power that far exceeds the regular languages. For example, the ability to group subexpressions with brackets and recall them in the same expression means that a pattern can match strings of repeated words like "papa" or "WikiWiki", called squares in formal language theory. The pattern for these strings is just "(.*)\1". However, the language of squares is not regular, nor is it context-free. Pattern matching with an unbounded number of back references, as supported by a number of modern tools, is NP-hard.

However, many tools, libraries, and engines that provide such constructions still use the term regular expression for their patterns. This has led to a nomenclature where the term "regular expression" has different meanings in formal language theory and pattern matching. It has been suggested to use the term regex or simply "pattern" for the latter. Larry Wall (author of Perl) writes in Apocalypse 5:

"'[R]egular expressions' […] are only marginally related to real regular expressions. Nevertheless, the term has grown with the capabilities of our pattern matching engines, so I'm not going to try to fight linguistic necessity here. I will, however, generally call them "regexes" (or "regexen", when I'm in an Anglo-Saxon mood)."

Implementations and running times

There are at least two different algorithms that decide if (and how) a given string matches a regular expression.

The oldest and fastest relies on a result in formal language theory that allows every Nondeterministic Finite State Machine (NFA) to be transformed into a deterministic finite state machine (DFA). The algorithm performs or simulates this transformation and then runs the resulting DFA on the input string, one symbol at a time. The latter process takes time linear to the length of the input string. More precisely, an input string of size n can be tested against a regular expression of size m in time O(n+2m) or O(nm), depending on the details of the implementation. This algorithm is often referred to as DFA. It is fast, but can be used only for matching and not for recalling grouped subexpressions. There is a variant that can recall grouped subexpressions, but its running time slows down to O(n2m) [citation needed].

The other algorithm is to match the pattern against the input string by backtracking. (This algorithm is sometimes called NFA, but this terminology is highly confusing.) Its running time can be exponential, which simple implementations exhibit when matching against expressions like "(a|aa)*b" that contain both alternation and unbounded quantification and force the algorithm to consider an exponential number of subcases. More complex implementations identify and speed up various common cases where they would otherwise run slowly.

Even though backtracking implementations only give an exponential guarantee in the worst case, they allow much greater flexibility and provide more expressive power. For instance any implementation that allows the use of backreferences, or implements the various improvements that Perl introduced, must use a backtracking implementation.

Some implementations try to provide the best of both algorithms by first running a fast DFA match to see if the string matches the regular expression at all, and only in that case perform a potentially slower backtracking match.

Regular expressions and Unicode

Regular expressions were originally used with ASCII characters. Many regular expression engines can now handle Unicode. In most respects it makes no difference what the character set is, but certain issues do arise in the extension of regular expressions to Unicode.

One issue is which Unicode format is supported. All command-line regular expression engines expect UTF-8, but regular expression libraries vary. Some expect UTF-8, while others expect other encodings of Unicode (UTF-16, obsolete UCS-2 or UTF-32).

A second issue is whether the full Unicode range is supported. Many regular expression engines support only the Basic Multilingual Plane, that is, the characters encodable in only 16 bits. Only a few regular expression engines can at present handle the full 21 bit Unicode range.

A third issue is variation in how ASCII-oriented constructs are extended to Unicode. For example, in ASCII-based implementations, character ranges of the form [x-y] are valid wherever x and y are codepoints in the range [0x00,0x7F] and codepoint(x) <= codepoint(y). The natural extension of such character ranges to Unicode would simply change the requirement that the endpoints lie in [0x00,0x7F] to the requirement that they lie in [0,0x10FFFF]. However, in practice this is often not the case. Some implementations, such as that of gawk, do not allow character ranges to cross Unicode blocks. A range like [0x61,0x7F] is valid since both endpoints fall within the Basic Latin block, as is [0x0530,0x0560] since both endpoints fall within the Armenian block, but a range like [0x0061,0x0532] is invalid since it includes multiple Unicode blocks. Other engines, such as that of the Vim editor, allow block-crossing but limit the number of characters in a range to 128.

Another area in which there is variation is in the interpretation of case-insensitive flags. Some such flags affect only the ASCII characters. Others flags affect all characters. Some engines have two different flags, one for ASCII, the other for Unicode. Exactly which characters belong to the POSIX classes also varies.

Another response to Unicode has been the introduction of character classes for Unicode blocks and Unicode general character properties. In Perl and in the Java library java.util.regex, classes of the form \p{InX} match characters in block X and \P{InX} match the complement. For example, \p{Armenian} matches any character in the Armenian block. Similarly, \p{X} matches any character with the general character property X and \P{X} the complement. For example, \p{Lu} matches any upper-case letter.

Uses of regular expressions

Regular expressions are particularly useful in the production of code completion systems and syntax highlighting in integrated development environments (IDEs). For example

(public|private|protected|)\s*(\w+)\s+(\w+)\s*\(

would match functions in many programming languages.

See also

Notes

  1. ^ Wall, Larry and the Perl 5 development team (2006). "perlre: Perl regular expressions".{{cite web}}: CS1 maint: numeric names: authors list (link)
  2. ^ Wall, Larry (2002-06-04). "Apocalypse 5: Pattern Matching".

References

Articles