Regular expression |
A regular expression (abbreviated as regexp, regex, or regxp, with plural forms regexps, regexes, or regexen) is a string (computer science) 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.
=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). As a side note, there are usually multiple different patterns describing any given set. Most formalisms provide the following operations to construct regular expressions.
;alternation :A vertical bar separates alternatives. For example, gray|grey matches 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, colour 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 , etc. :;+ ::The plus sign indicates that there is at least 1 of the previous expression. For example, go+gle matches gogle , google , 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 )(father|mother) 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, and is described in more detail below.
=History=
The origin of regular expressions lies in .
Perl regular expressions were derived from .
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 [http://dev.perl.org/perl6 Perl6] is improving this integration. This is the subject of [http://dev.perl.org/perl6/apocalypse/A05.html Apocalypse 5].
=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:
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:
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 .
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 #Patterns for irregular languages 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-expressionaware Unix utilities, for example Grep and Sed , use it by default.
In this syntax, most characters are treated as literalsthey match only themselves ( a matches a , (bc matches (bc , etc). The exceptions are called metacharacters:
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:
example: [[:upper:]ab] should only return the uppercase letters and lowercase a and b .
==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 escape sequence 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 but 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 you can specify with Perl but not POSIX is whether you want part of the match 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 — Python programming language, exim, and BBEdit, for example. But you can t believe all claims that Perl-compatible regular expressions are available. For instance Tcl tries to both follow the POSIX specification and implement Perl s extensions. Unfortunately this means that TCL s definition of a non-greedy match is, Match as little as you can here while still having the overall match be as long as possible. So in the above example, both patterns will match the whole string.
==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. There is a variant that can recall grouped subexpressions, but its running time slows down to O ( n2m ).
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.
=See also=
=References=
=External links=
*[http://zvon.org/other/reReference/Output/index.html ZVON Regular Expression Reference] *[http://dmoz.org/Computers/Programming/Languages/Regular_Expressions/ DMOZ listing] *[http://www.regexlib.com/ Regular Expression Library] Currently contains over 1000 expressions from contributors around the world. *[http://www.regular-expressions.info Regular Expression Tutorial and Reference] One of the most comprehensive, free regular expression tutorials on the net. *[http://etext.lib.virginia.edu/services/helpsheets/unix/regex.html Using Regular Expressions] *Articles: **[http://cm.bell-labs.com/cm/cs/who/dmr/qed.html An Incomplete History of the QED Text Editor] **[http://gnosis.cx/publish/programming/regular_expressions.html Learning to Use Regular Expressions] Brief regular expression tutorial by David Mertz **[http://wiki.castlecops.com/A_list_of_Regex_topics A List of Regex Topics] Wiki with various topics about regular expressions. **[http://www.regex.info/ Mastering Regular Expressions ] Official website for Jeffrey Friedl s book. **[http://www.greenend.org.uk/rjk/2002/06/regexp.html Regexp Syntax Summary] Reference table for UNIX grep, Emacs, Perl, Python and Tcl regular expressions. **[http://www.regenechsen.de/phpwcms/index.phpregex_englisch Regenechsen] Beginners regular expression tutorial with exercises.
|
|