FACTOID # 46: Japan has 53 working nuclear reactors and is planning to build another 12.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Regular expression

In computing, a regular expression is a string that is used to describe or match a set of strings, according to certain syntax rules. For the formal concept of computation, see computation. ... In computer programming and formal language theory, (and other branches of mathematics), a string is an ordered sequence of symbols. ... In computer science, the set is a collection of certain values without any particular order. ... For other uses, see Syntax (disambiguation). ...


Regular expressions are used by many text editors, utilities, and programming languages to search and manipulate text based on patterns. For example, Perl and Tcl have a powerful regular expression engine built directly into their syntax. Several utilities provided by Unix distributions—including the editor ed and the filter grep—were the first to popularize the concept of regular expressions. "Regular expression" is often shortened to regex or regexp (singular), or regexes, regexps, or regexen (plural). Some authors distinguish between regular expression and abbreviated forms such as regex, restricting the former to true regular expressions, which describe regular languages, while using the latter for any regular expression-like pattern, including those that describe languages that are not regular. As only some authors observe this distinction, it is not safe to rely upon it.[citation needed] Notepad is the standard text editor for Microsoft Windows A text editor is a piece of computer software for editing plain text. ... Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ... Tcl (originally from Tool Command Language, but nonetheless conventionally rendered as Tcl rather than TCL; and pronounced tickle) is a scripting language created by John Ousterhout. ... Filiation of Unix and Unix-like systems Unix (officially trademarked as UNIX®, sometimes also written as or ® with small caps) is a computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs including Ken Thompson, Dennis Ritchie and Douglas McIlroy. ... ed was the original standard text editor on the Unix operating system. ... grep is a command line utility that was originally written for use with the Unix operating system. ... In theoretical computer science, a regular language is a formal language (i. ...


As an example of the syntax, the regular expression bex can be used to search for all instances of the string "ex" that occur at word boundaries (signified by the b). Thus in the string, "Texts for experts," bex matches the "ex" in "experts," but not in "Texts" (because the "ex" occurs inside the word there and not immediately after a word boundary).


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 also known as globbing. Wildcards differ from regular expressions in that they generally only express very restrictive forms of alternation. The term wildcard character has the following meanings: // In telecommunications, a wildcard character is a character that may be substituted for any of a defined subset of all possible characters. ... For library and office filing systems, see Library classification. ... In computing, a shell is a piece of software that provides an interface for users (command line interpreter). ... glob() is a Unix library function that expands file names using a pattern matching notation reminiscent of regular expression syntax but without the expressive power of true regular expressions. ...

Contents

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 can match "gray" or "grey".
Grouping
Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gray|grey and gr(a|e)y are equivalent patterns which both describe the set of "gray" and "grey".
Quantification
A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed to occur. The most common quantifiers are ?, *, and +.
? The question mark indicates there is zero or one of the preceding element. For example, colou?r matches both "color" and "colour".
* The asterisk indicates there are zero or more of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.
+ The plus sign indicates that there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".

These constructions can be combined to form arbitrarily complex expressions, much like one can construct arithmetical expressions from numbers and the operations +, -, *, and /. For example, H(ae?|ä)ndel and H(a|ae|ä)ndel are both valid patterns which match the same strings as the earlier example, H(ä|ae?)ndel.


The precise syntax for regular expressions varies among tools and with context; more detail is given in the Syntax section. For other uses, see Syntax (disambiguation). ...


History

The origins of regular expressions lie 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. In the 1950s, mathematician Stephen Cole Kleene described these models using his mathematical notation called regular sets. The SNOBOL language was an early implementation of pattern matching, but not identical to regular expressions. Ken Thompson built Kleene's 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). Since that time, many variations of Thompson's original adaptation of regular expressions have been widely used in Unix and Unix-like utilities including expr, AWK, Emacs, vi, and lex. “Automata” redirects here. ... In mathematics, logic, and computer science, a formal language is a language that is defined by precise mathematical or machine processable formulas. ... Computer science (informally, CS or compsci) is, in its most general sense, the study of computation and information processing, both in hardware and in software. ... Stephen Cole Kleene (January 5, 1909 – January 25, 1994) was an American mathematician whose work at the University of Wisconsin-Madison helped lay the foundations for theoretical computer science. ... SNOBOL (StriNg Oriented symBOlic Language) is a computer programming language developed between 1962 and 1967 at AT&T Bell Laboratories by David J. Farber, Ralph E. Griswold and Ivan P. Polonsky. ... In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. ... Kenneth Thompson redirects here. ... QED is a line-oriented computer text editor. ... ed was the original standard text editor on the Unix operating system. ... grep is a command line utility that was originally written for use with the Unix operating system. ... expr is a command line Unix utility which evaluates an expression and outputs the corresponding value. ... AWK is a general purpose computer language that is designed for processing text-based data, either in files or data streams. ... This article is about the text editor. ... vi editing a temporary, empty file. ... lex is a program that generates lexical analyzers (scanners or lexers). Lex is commonly used with the yacc parser generator. ...


Perl and Tcl regular expressions were derived from a regex library written by Henry Spencer, though Perl later expanded on Spencer's 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 including PHP and Apache HTTP Server. 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 existing features of Perl 5.x regular expressions, but also allow BNF-style definition of a recursive descent parser via sub-rules. Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ... Tcl (originally from Tool Command Language, but nonetheless conventionally rendered as Tcl rather than TCL; and pronounced tickle) is a scripting language created by John Ousterhout. ... Henry Spencer is a co-author of C News and The Ten Commandments for C Programmers. ... Philip Hazel is a computer programmer best known for writing the Exim mail transport agent and the PCRE library. ... Perl Compatible Regular Expressions (PCRE) is a regular expression C library inspired by Perls external interface, written by Philip Hazel. ... For other uses, see PHP (disambiguation). ... The Apache HTTP Server, commonly referred to simply as Apache, is a web server notable for playing a key role in the initial growth of the World Wide Web. ... Perl 6 is a planned major revision to the Perl programming language. ... A parsing expression grammar, or PEG, is a type of analytic formal grammar that describes a formal language in terms of a set of rules for recognizing strings in the language. ... Perl 6 rules are Perl 6s regular expression, pattern matching and general-purpose parsing facility, and are a core part of the language. ... The Backus–Naur form (also known as BNF, the Backus–Naur formalism, Backus normal form, or Panini–Backus Form) is a metasyntax used to express context-free grammars: that is, a formal way to describe formal languages. ... A recursive descent parser is a top-down parser built from a set of mutually-recursive procedures (or a non-recursive equivalent) where each such procedure usually implements one of the production rules of the grammar. ...


The use of regular expressions in structured information standards for document and database modeling 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. Simple use is evident in the DTD element group syntax. The Standard Generalized Markup Language (SGML) is a metalanguage in which one can define markup languages for documents. ... An XML schema is a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic syntax constraints imposed by XML itself. ... Document Type Definition (DTD), defined slightly differently within the XML and SGML (the language XML was derived from) specifications, is one of several SGML and XML schema languages, and is also the term used to describe a document or portion thereof that is authored in the DTD language. ...


See also Pattern matching: History. In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. ...


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: In mathematics, logic, and computer science, a formal language is a language that is defined by precise mathematical or machine processable formulas. ...

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

The following operations are defined: A string literal is the representation of a string value within the source code of a computer program. ...

  • (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. In mathematical logic and computer science, the Kleene star (or Kleene closure) is a unary operation, either on sets of strings or on sets of symbols or characters. ... “Superset” redirects here. ... In mathematics, a set is said to be closed under some operation if the operation on members of the set produces a member of the set. ... In mathematics, a Kleene algebra (named after Stephen Cole Kleene, pronounced clay-knee) is either of two different things: A bounded distributive lattice with an involution satisfying De Morgans laws, and the inequality x∧−x ≤ y∨−y. ...


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 can be 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 with no symbols other than a and b, including the empty string
  • ab*(c|ε) denotes the set of strings starting with a, then zero or more bs and finally optionally a c.

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, as it can always be expressed by using the other operators (although the process for computing such a representation is complex, and the result may be exponentially larger).


Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by finite state automata. 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. 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. In theoretical computer science, a regular language is a formal language (i. ... Fig. ... In mathematics, exponential growth (or geometric growth) occurs when the growth rate of a function is always proportional to the functions current size. ... In computer science and linguistics, a formal grammar, or sometimes simply grammar, is a precise description of a formal language — that is, of a set of strings. ... The Chomsky hierarchy is a containment hierarchy of classes of formal grammars that generate formal languages. ... In the theory of computation, a nondeterministic finite state machine or nondeterministic finite automaton (NFA) is a finite state machine where for each pair of state and input symbol there may be several possible next states. ...


We can also study expressive power within the formalism. As the examples show, 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 machine, and determines whether they are isomorphic (equivalent). In mathematics, computing, linguistics, and related disciplines, an algorithm is a finite list of well-defined instructions for accomplishing some task that, given an initial state, will terminate in a defined end-state. ... In mathematics, an isomorphism (in Greek isos = equal and morphe = shape) is a kind of mapping between objects, devised by Eilhard Mitscherlich, which shows a relation between two properties or operations. ...


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. The lack of axiomatization in the past led to the star height problem. Recently, Dexter Kozen axiomatized regular expressions with Kleene algebra. The star-height problem in formal language theory is the question whether all regular languages can be expressed using regular expressions with a limited nesting depth of Kleene stars. ... In mathematics, a Kleene algebra (named after Stephen Cole Kleene, pronounced clay-knee) is either of two different things: A bounded distributive lattice with an involution satisfying De Morgans laws, and the inequality x∧−x ≤ y∨−y. ...


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 backwards compatibility. Many regular-expression-aware Unix utilities including grep and sed use it by default while providing support for extended regular expressions with command line arguments. Filiation of Unix and Unix-like systems Unix (officially trademarked as UNIX®, sometimes also written as or ® with small caps) is a computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs including Ken Thompson, Dennis Ritchie and Douglas McIlroy. ... POSIX or Portable Operating System Interface[1] is the collective name of a family of related standards specified by the IEEE to define the application programming interface (API) for software compatible with variants of the Unix operating system. ... grep is a command line utility that was originally written for use with the Unix operating system. ... The correct title of this article is . ... In computer command line interfaces, a command line argument is an argument sent to a program being called. ...


In the basic syntax, most characters are treated as literals — they match only themselves (i.e., a matches "a"). The exceptions, listed below, are called metacharacters. Look up literal, literally in Wiktionary, the free dictionary. ... A metacharacter is a character that has a general meaning instead of a literal meaning in a regular expression. ...

. Matches any single character except newline. Within square brackets, the dot character matches a literal dot. For example, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c".
[ ] Matches a single character that is contained within the brackets. For example, [abc] matches "a", "b", or "c". [a-z] specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: [abcx-z] matches "a", "b", "c", "x", "y", and "z", as does [a-cx-z].

The - character is treated as a literal character if it is the last or the first character within the brackets, or if it is escaped with a backslash: [abc-], [-abc], or [a-bc]. The [ character can be included anywhere within the brackets. To match the ] character, the easiest way is to escape it with a backslash, e.g., []]. Some tools allow you to avoid the backslash if the closing bracket is first in the enclosing square brackets, e.g., [][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 from "a" to "z". As above, literal characters and ranges can be mixed.
^ Matches the starting position within the string. In multiline mode, it matches the starting position of any line.
$ Matches the ending position of the string or the position just before a string-terminating newline. In multiline mode, it matches the ending position of any line.
( ) Defines a marked subexpression. The string matched within the parentheses can be recalled later (see the next entry, n. A marked subexpression is also called a block or capturing group. This feature is not found in all instances of regular expressions, and in many Unix utilities including sed and vi, a backslash must precede the open and close parentheses for them to be interpreted with special meaning.
n Matches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is theoretically irregular and was not adopted in the POSIX extended regular expression (ERE) syntax. Some tools allow referencing more than nine capturing groups.
* Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc. [xyz]* matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. (ab)* matches "", "ab", "abab", "ababab", and so on.
{m,n} Matches the preceding element at least m and not more than n times. For example, a{3,5} matches only "aaa", "aaaa", and "aaaaa". This is not found in a few, older instances of regular expressions.

Note that particular implementations of regular expressions interpret backslash differently in front of some of the metacharacters. For example, egrep and Perl interpret non-backslashed parentheses, vertical bars, and curly brackets as metacharacters, reserving the backslashed versions to mean the literal characters themselves. Old versions of grep did not support the alternation operator |. The correct title of this article is . ... vi editing a temporary, empty file. ...


Examples:

  • .at matches any three-character string ending with "at", including "hat", "cat", and "bat".
  • [hc]at matches "hat" and "cat".
  • [^b]at matches all strings matched by .at except "bat".
  • ^[hc]at matches "hat" and "cat", but only at the beginning of the string or line.
  • [hc]at$ matches "hat" and "cat", but only at the end of the string or line.

POSIX extended regular expressions

POSIX extended regular expressions (ERE), as defined by IEEE POSIX standard 1003.2, are similar in syntax to the traditional Unix regular expressions, with some exceptions. The following metacharacters are added: POSIX or Portable Operating System Interface[1] is the collective name of a family of related standards specified by the IEEE to define the application programming interface (API) for software compatible with variants of the Unix operating system. ... Not to be confused with the Institution of Electrical Engineers (IEE). ... The Single UNIX Specification (SUS) is the collective name of a family of standards for computer operating systems to qualify for the name Unix. The SUS is developed and maintained by the Austin Group, based on earlier work by the IEEE and The Open Group. ...

? Matches the preceding element zero or one time. For example, ba? matches "b" or "ba".
+ Matches the preceding element one or more times. For example, ba+ matches "ba", "baa", "baaa", and so on.
| The choice (aka alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

Additionally, some backslashes are removed: {...} becomes {...}, and (...) becomes (...).


Examples:

  • [hc]+at matches "hat", "cat", "hhat", "chat", "hcat", "ccchat", and so on, but not "at".
  • [hc]?at matches "hat", "cat", and "at".
  • cat|dog matches "cat" or "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. To meet Wikipedias quality standards, this article or section may require cleanup. ...


Extended POSIX regular expressions can often be used with modern Unix utilities by including the command line flag -E. A command line interface or CLI is a method of interacting with a computer by giving it lines of textual commands (that is, a sequence of characters) either from keyboard input or from a script. ...


POSIX bracket expressions

Since many ranges of characters depend on the chosen locale setting (i.e., in some settings letters are organized as abc...zABC...Z, while in some others as aAbBcC...zZ), the POSIX standard defines some classes or categories of characters as shown in the following table:

POSIX ASCII Description
[:alnum:] [A-Za-z0-9] Alphanumeric characters
[:alpha:] [A-Za-z] Alphabetic characters
[:blank:] [ t] Space and tab
[:cntrl:] [&# 0;-] Control characters
[:digit:] [0-9] Digits
[:graph:] [!-~] Visible characters
[:lower:] [a-z] Lowercase letters
[:print:] [ -~] Visible characters and spaces
[:punct:] [!"#$%&'()*+,-./:;?@[]_`{|}~] Punctuation characters
[:space:] [ trnvf] Whitespace characters
[:upper:] [A-Z] Uppercase letters
[:xdigit:] [A-Fa-f0-9] Hexadecimal digits

For example, [[:upper:]ab] matches the uppercase letters and lowercase "a" and "b".


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. Vim, which stands for Vi IMproved, is an open source, multiplatform text editor extended from vi. ...


Perl-derivative regular expressions

Perl has a richer and more predictable syntax than the POSIX basic (BRE) and extended (ERE) regular expression standards. An example of its predictability is that always escapes a non-alphanumeric character. An example of functionality possible through Perl but not POSIX-compliant regular expressions is the concept of lazy quantification (see the next section). Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ...


Due largely to its expressive power, many other utilities have adopted syntaxes very similar to Perl's — for example, Java, JavaScript, PCRE, Python, Ruby, and Microsoft's .NET Framework all use regular expression syntax similar to Perl's. Some languages and tools such as PHP support multiple regular expression engine types. Perl-derivative regular expression implementations are not identical, and many implement only a subset of Perl's features. With Perl 5.9.x (development track for Perl 5.10), this process has come full circle with Perl incorporating syntax extensions originally from Python, the .NET Framework, and Java. Java language redirects here. ... JavaScript is a scripting language most often used for client-side web development. ... Perl Compatible Regular Expressions (PCRE) is a regular expression C library inspired by Perls external interface, written by Philip Hazel. ... Python is a high-level programming language first released by Guido van Rossum in 1991. ... Ruby is a reflective, dynamic, object-oriented programming language. ... Microsoft Corporation, (NASDAQ: MSFT, HKSE: 4338) is a multinational computer technology corporation with global annual revenue of US$44. ... The Microsoft . ... For other uses, see PHP (disambiguation). ...


Lazy quantification

The standard quantifiers in regular expressions are greedy, meaning they match as much as they can, only giving back as necessary to match the remainder of the regex. For example, someone new to regexes wishing to find the first instance of an item between < and > symbols in this example:

 Another whale explosion occurred on <January 26>, <2004>. 

...would likely come up with the pattern <.*>, or similar. However, this pattern will actually return "<January 26>, <2004>" instead of the "<January 26>" which might be expected, because the * quantifier is greedy — it will consume as many characters as possible from the input, and "January 26>, <2004" has more characters than "January 26".


Though this problem can be avoided in a number of ways (e.g., by specifying the text that is not to be matched: <[^>]*>), modern regular expression tools allow a quantifier to be specified as lazy (also known as non-greedy, reluctant, minimal, or ungreedy) by putting a question mark after the quantifier (e.g., <.*?>), or by using a modifier which reverses the greediness of quantifiers (though changing the meaning of the standard quantifiers can be confusing). By using a lazy quantifier, the expression tries the minimal match first. Though in the previous example lazy matching is used to select one of many matching results, in some cases it can also be used to improve performance when greedy matching would require more backtracking. Backtracking is a type of algorithm that is a refinement of brute force search. ...


Patterns for non-regular languages

Many patterns provide an expressive power that far exceeds the regular languages. For example, the ability to group subexpressions with parentheses and recall the value they match 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 (.*)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 numerous modern tools, is NP-hard. In theoretical computer science, a regular language is a formal language (i. ... The introduction to this article provides insufficient context for those unfamiliar with the subject matter. ... In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. ... In computational complexity theory, NP-hard (Non-deterministic Polynomial-time hard) refers to the class of decision problems that contains all problems H such that for all decision problems L in NP there is a polynomial-time many-one reduction to H. Informally this class can be described as containing...


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. For this reason, some people have taken to using the term regex or simply pattern to describe the latter. Larry Wall (author of Perl) writes in Apocalypse 5: In mathematics, logic, and computer science, a formal language is a language that is defined by precise mathematical or machine processable formulas. ... Larry Wall Larry Wall (born September 27, 1954) is a programmer, linguist, and author, most widely known for his creation of the Perl programming language in 1987. ...

'Regular 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 fundamentally different algorithms that decide if and how a given regular expression matches a string. In mathematics, computing, linguistics, and related disciplines, an algorithm is a finite list of well-defined instructions for accomplishing some task that, given an initial state, will terminate in a defined end-state. ...


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 only be used for matching and not for recalling grouped subexpressions, lazy quantification, and several other features commonly found in modern regular expression libraries. In the theory of computation, a nondeterministic finite state machine or nondeterministic finite automaton (NFA) is a finite state machine where for each pair of state and input symbol there may be several possible next states. ... In the theory of computation, a deterministic finite state machine or deterministic finite automaton (DFA) is a finite state machine where for each pair of state and input symbol there is one and only one transition to a next state. ...


The other algorithm is to match the pattern against the input string by backtracking. This algorithm is commonly called NFA, but this terminology can be 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 sub-cases. More complex implementations will often identify and speed up or abort common cases where they would otherwise run slowly. Backtracking is a type of algorithm that is a refinement of brute force search. ...


Although backtracking implementations give an exponential guarantee in the worst case, they provide much greater flexibility and expressive power. For example, any implementation which allows the use of backreferences, or implements the various improvements introduced by Perl, 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 some issues do arise when extending regular expressions to support Unicode. There are 95 printable ASCII characters, numbered 32 to 126. ... The Unicode Standard, Version 5. ...


One issue is which Unicode format is supported. Some regular expression libraries expect the UTF-8 encoding, while others might expect UTF-16, obsolete UCS-2, or UTF-32. UTF-8 (8-bit UCS/Unicode Transformation Format) is a variable-length character encoding for Unicode. ... In computing, UTF-16 is a 16-bit Unicode Transformation Format, a character encoding form that provides a way to represent a series of abstract characters from Unicode and ISO/IEC 10646 as a series of 16-bit words suitable for storage or transmission via data networks. ... In computing, UCS-2 and UTF-16 are alternative names for a 16-bit Unicode Transformation Format, a character encoding form that provides a way to represent a series of abstract characters from Unicode and ISO/IEC 10646 as a series of 16-bit words suitable for storage or transmission... UTF-32 is a method of encoding Unicode characters, using a fixed amount of 32 bits for each character. ...


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 which can be encoded with only 16 bits. Currently, only a few regular expression engines can handle the full 21-bit Unicode range. Unicode’s Universal Character Set potentially supports over 1 million (1,114,112 = 220 + 216 or 17 × 216, hexadecimal 110000) code points. ...


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. ... Vim, which stands for Vi IMproved, is an open source, multiplatform text editor extended from vi. ...


Another area in which there is variation is in the interpretation of case-insensitive flags. Some such flags affect only the ASCII characters. Other 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 the java.util.regex library, classes of the form p{InX} match characters in block X and P{InX} match the opposite. Similarly, p{Armenian} matches any character in the Armenian block, and p{X} matches any character with the general character property X. For example, p{Lu} matches any upper-case letter. Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ...


Uses of regular expressions

See also: Regular expression examples

Regular expressions are useful in the production of code completion systems and syntax highlighting in integrated development environments (IDEs), data validation and many other tasks. A regular expression ( also RegEx or regex ) is a string that is used to describe or match a set of strings, according to certain syntax rules. ... Autocomplete is a feature provided by many source code text editors, word processors, and web browsers. ... HTML syntax highlighting Syntax highlighting is a feature of some text editors that displays text—especially source code—in different colors and fonts according to the category of terms. ... An integrated development environment (IDE), also known as integrated design environment and integrated debugging environment, is a programming environment that has been packaged as an application program,that assists computer programmers in developing software. ...


While regular expressions would be useful on search engines such as Google or Live Search, processing them across the entire database could consume massive amounts of resources depending on the complexity and design of the regex. Although in many cases system administrators can run regex-based queries internally, most search engines do not offer regex support to the public. A notable exception is Google Code Search. A search engine is an information retrieval system designed to help find information stored on a computer system. ... This article is about the corporation. ... It has been suggested that MSN Search be merged into this article or section. ... Google Code Search is a free beta product from Google which debuted in Google Labs on October 5, 2006 allowing web users to search for open-source code on the Internet. ...


See also

// ^  formerly called Regex++ ^  included since version 2. ... The extended Backus–Naur form (EBNF) is an extension of the basic Backus–Naur form (BNF) metasyntax notation. ... Ragel is a finite state machine compiler with output support for C, C++, Objective-C and D source code. ... In Computer Science, a regular tree grammar is a formal grammar that allows to generate trees. ... RegexBuddy is a regular expression tool by Just Great Software for the Microsoft Windows operating system. ...

Notes

  1. ^ Wall, Larry and the Perl 5 development team (2006). perlre: Perl regular expressions.
  2. ^ Wall, Larry (2002-06-04). Apocalypse 5: Pattern Matching.

Larry Wall Larry Wall (born September 27, 1954) is a programmer, linguist, and author, most widely known for his creation of the Perl programming language in 1987. ... Larry Wall Larry Wall (born September 27, 1954) is a programmer, linguist, and author, most widely known for his creation of the Perl programming language in 1987. ... Also see: 2002 (number). ... is the 155th day of the year (156th in leap years) in the Gregorian calendar. ...

References

  • Forta, Ben. Sams Teach Yourself Regular Expressions in 10 Minutes. Sams. ISBN 0-672-32566-7. 
  • Friedl, Jeffrey. Mastering Regular Expressions. O'Reilly. ISBN 0-596-00289-0. 
  • Habibi, Mehran. Real World Regular Expressions with Java 1.4. Springer. ISBN 1-59059-107-0. 
  • Liger, Francois; Craig McQueen, Paul Wilton. Visual Basic .NET Text Manipulation Handbook. Wrox Press. ISBN 1-86100-730-2. 
  • Sipser, Michael. "Chapter 1: Regular Languages", Introduction to the Theory of Computation. PWS Publishing, 31–90. ISBN 0-534-94728-X. 
  • Stubblebine, Tony. Regular Expression Pocket Reference. O'Reilly. ISBN 0-596-00415-X. 

Ben Forta is an author and Senior Technical Evangelist for Adobe Systems focussed primarily on ColdFusion. ... Jeffrey Friedl (born 1966, Friedl sounds like free-dole) is a software engineer known for his book on regular expressions, Mastering Regular Expressions (OReilly 1997, 2002). ... Programming Perl is a classic OReilly book. ... One of Wrox books Wrox press (established in 1992) is a computer book publisher, based in the UK. Wrox has pioneered the philosophy of Programmer to Programmer&#8482; books for technology professionals. ... Michael Sipser Michael Sipser is a professor of Applied Mathematics in the Theory of Computation Group at the Massachusetts Institute of Technology. ...

External links

Wikibooks
Wikibooks has a book on the topic of
Regular Expressions

  Results from FactBites:
 
PlanetMath: regular expression (517 words)
Here is an example of a regular expression that specifies a grammar that generates the binary representation of all multiples of 3 (and only multiples of 3).
A little further work is required to transform this grammar into an acceptable form for regular grammars, but it can be shown that this grammar (and any grammar specified by a regular expression) is equivalent to some regular grammar.
This is version 12 of regular expression, born on 2002-02-24, modified 2007-11-13.
Pattern (Java 2 Platform SE v1.4.2) (1992 words)
A regular expression, specified as a string, must first be compiled into an instance of this class.
Compiles the given regular expression and attempts to match the given input against it.
Returns the regular expression from which this pattern was compiled.
  More results at FactBites »


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments
Please enter the 5-letter protection code

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.