Regular expression
|
A regular expression (abbreviated as regexp, regex, or regxp, 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 has a powerful regular expression engine built directly into its syntax. The set of utilities (including the editor sed and the filter grep) provided by Unix distributions were the first to popularize the concept of regular expressions.
Contents |
Basic concepts
A regular expression, often called a pattern, is an expression that describes a set of strings without actually listing its elements. For example, the three strings Handel, Händel, and Haendel are described by the pattern "H(ä|ae?)ndel". Most formalisms provide the following constructions, which are introduced here by example.
- alternation
- A vertical bar separates alternatives. For example, "gray|grey" matches grey or gray.
- quantification
- A quantifier after a character specifies how often that character is allowed to occur. The most common quantifiers are +, ?, and *:
- +
- The plus sign indicates that the preceding character must be present at least once. For example, "goo+gle" matches the infinite set google, gooogle, goooogle, etc. (but not gogle).
- ?
- The question mark indicates that the preceding character may be present at most once. For example, "colou?r" matches color and colour.
- *
- The asterisk indicates that the preceding character may be present zero, one, or more times. For example, "0*42" matches 42, 042, 0042, etc.
- grouping
- Parentheses are used to define the scope and precedence of the other operators. For example, "gr(a|e)y" is the same as "gray|grey", and "(grand)?father" matches both father and grandfather.
The constructions can be freely combined within the same expression, so that "H(ae?|ä)ndel" is the same as "H(a|ae|ä)ndel".
The precise syntax for regular expressions varies among tools and application areas, and is described in more detail below.
History
The origin of regular expressions lies in automata theory and formal language theory (both part of theoretical computer science). These fields study models of computation (automata) and ways to describe and classify formal languages. In the 1940s, Warren McCulloch and Walter Pitts described the nervous system by modelling neurons as small simple automata. The mathematician Stephen Kleene later described these models using his mathematical notation called regular sets. Ken Thompson built this notation into the editor QED, then into the Unix editor ed and eventually into grep. Ever since that time, regular expressions have been widely used in Unix and Unix-like utilities such as: expr, awk, Emacs, vi, lex, and Perl.
Perl regular expressions were derived from regex written by Henry Spencer. Philip Hazel developed pcre (http://www.pcre.org/) (Perl Compatible Regular Expressions) which attempts to closely mimic Perl's regular expression functionality, and is used by many modern tools such as Python, PHP, and Apache.
The integration of regular expressions in most computer languages is still very poor and, even though Perl's regular expression integration is one of the best around, part of the effort in the design of the future Perl6 (http://dev.perl.org/perl6) is improving this integration. This is the subject of Apocalypse 5 (http://dev.perl.org/perl6/apocalypse/A05.html).
In 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", ... }.
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
- b*(ab*)* the same
- ab*(c|ε) denotes the set of strings starting with a, then zero or more bs and finally optionally a c.
- ((a|ba(aa)*b)(b(aa)*b)*(a|ba(aa)*b)|b(aa)*b)*(a|ba(aa)*b)(b(aa)*b)* denotes the set of all strings which contain an even number of bs and an odd number of as. Note that this regular expression is of the form (X Y*X U Y)*X Y* with X = a|ba(aa)*b and Y = b(aa)*b.
The formal definition of regular expressions is purposefully 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. In that case the resulting operators form a Kleene algebra. The complement operator is redundant: it can always be expressed by only using the other operators.
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 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.
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 equal - essentially, it 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.
Syntaxes
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, for example grep and sed, use it by default.
In this syntax, most characters are treated as literals—they match only themselves ("a" matches "a", "(bc" matches "(bc", etc). The exceptions are called metacharacters:
. | Matches any single character |
[ ] | 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) |
\( \) | Define a "marked subexpression". What the enclosed expression matched can be recalled later. See the next entry, \n. Note that a "marked subexpression" is also a "block" |
\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. |
* |
|
\{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. |
Old versions of grep did not support the alternation operator "|".
Examples:
- ".at" matches any three-character string ending with at
- "[hc]at" matches hat and cat
- "[^b]at" matches any three-character string ending with at and not beginning with b.
- "^[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 |
[:space:] | [ \t\n\r\f\v] | blank 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 return the upper letters and 'a' 'b' lower.
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" et cetera
- "[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" somehow 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:
- ".\.(\(|\))" matches with the string "a.)"
Perl-compatible regular expressions (PCRE)
Perl has a much richer syntax than even the extended POSIX regexp. In addition, its syntax is somewhat more predictable (for example, a backstroke always quotes a non-alphanumeric character). For these reasons, the Perl syntax has been adopted in other utilities and applications -- Tcl and exim, for example.
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-complete.
However, many tools, libraries, and engines that provide such constructions still use the term regular expression for their patterns. This has lead 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 in 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.
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 many 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. Even though backtracking implementations give no running time guarantee in the worst case, they allow much greater flexibility and provide more expressive power.
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.
See also
References
- Jeffrey Friedl: Mastering Regular Expressions (http://regex.info/), O'Reilly, ISBN 0-596-00289-0
- Tony Stubblebine: Regular Expression, Pocket Reference, O'Reilly, ISBN 0-596-00415-X
- Ben Forta: Sams Teach Yourself Regular Expressions in 10 Minutes, Sams, ISBN 0-672-32566-7
- Mehran Habibi: Real World Regular Expressions with Java 1.4, Springer, ISBN 1-59059-107-0
- Francois Liger, Craig McQueen, Paul Wilton: Visual Basic .NET Text Manipulation Handbook, Wrox Press, ISBN 1-86100-730-2
- Michael Sipser: Introduction to the Theory of Computation, PWS Publishing Company, ISBN 0-534-94728-X
External links
- Regular Expression Library (http://www.regexlib.com/) Currently we have indexed 926 expressions from contributors around the world.
- DMOZ listing (http://dmoz.org/Computers/Programming/Languages/Regular_Expressions/)
- Articles/Archives:
- Regexp Syntax Summary (http://www.greenend.org.uk/rjk/2002/06/regexp.html), reference table for different styles of regular expressions
- online regular expression archive (http://RegExLib.com/)
- Regular expression information (http://www.regular-expressions.info)
- Syntax and Semantics of Regular Expressions (http://www.xrce.xerox.com/competencies/content-analysis/fsCompiler/fssyntax.html) by Xerox Research Centre Europe
- Learning to Use Regular Expressions (http://gnosis.cx/publish/programming/regular_expressions.html) by David Mertz
- Mastering Regular Expressions book website (http://www.regex.info/)
- Regenechsen (http://www.regenechsen.de/regex_en/regex_1_en.html), Beginners tutorial for using Regular Expressions
- An incomplete history of the QED text editor (http://cm.bell-labs.com/cm/cs/who/dmr/qed.html)
- xpressive (http://boost-sandbox.sourceforge.net/libs/xpressive/doc/html/index.html)
- The GRETA Regular Expression Template Archive (http://research.microsoft.com/projects/greta/)
- Tools:
- Regular expression .NET online tester (http://www.miningtools.net/regextester.aspx)
- The Regex Coach (http://weitz.de/regex-coach/), a very powerful interactive learning system to hone your regexp skills
- ^txt2regex$ (http://txt2regex.sourceforge.net/), a Regular Expression Wizard that converts human sentences to regexps
- RegexBuilder (http://renschler.net/RegexBuilder/), Simple .NET tool to test regular expressions
- Tcl Regular Expression Visualiser (http://www.doulos.com/knowhow/tcltk/examples/trev/)
- JRegexpTester (http://jregexptester.sourceforge.net/), free java regexp testing tool
- Boost.Regex: Index (http://www.boost.org/libs/regex/doc/index.html), boost.regex library for regular expression parser in C++
- The Regulator (http://regex.osherove.com/) The Regulator is an advanced, free regular expressions testing and learning tool. It allows you to build and verify a regular expression against any text input, file or web, and displays matching, splitting or replacement results within an easy to understand, hierarchical tree.
- PCRE Workbench (http://www.renatomancuso.com/software/pcreworkbench/pcreworkbench.htm)cs:Regulární výraz
da:Regulære udtryk de:Regulärer Ausdruck es:Expresión regular fr:Expression régulière is:Regluleg segð it:Espressione regolare ja:正規表現 nl:Reguliere expressie pl:Wyrażenia regularne pt:Expressão regular ru:Регулярное выражение fi:Säännöllinen lauseke zh:正则表达式