All Topics  
Regular expression

 

   Email Print
   Bookmark   Link






 

Regular expression



 
 
In computing
Computing

Computing is usually defined as the activity of using and developing computer technology, computer hardware and computer software. It is the computer-specific part of information technology....
, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language
Formal language

A formal language is a set of words, i.e. finite string of letters, or symbols. The inventory from which these letters are taken is called the alphabet over which the language is defined....
 that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification
Specification (technical standard)

A specification is an explicit set of requirements to be satisfied by a material, product, or service. ...
.

The following examples illustrate a few specifications that could be expressed in a regular expression:



Regular expressions can be much more complex than these examples.

Regular expressions are used by many text editor
Text editor

A text editor is a type of software application used for editing plain text files.Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code....
s, utilities, and programming languages to search and manipulate text based on pattern
Pattern

A pattern, from the French language patron, is a type of theme of recurring events of or objects, sometimes referred to as elements of a set....
s.






Discussion
Ask a question about 'Regular expression'
Start a new discussion about 'Regular expression'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computing
Computing

Computing is usually defined as the activity of using and developing computer technology, computer hardware and computer software. It is the computer-specific part of information technology....
, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language
Formal language

A formal language is a set of words, i.e. finite string of letters, or symbols. The inventory from which these letters are taken is called the alphabet over which the language is defined....
 that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification
Specification (technical standard)

A specification is an explicit set of requirements to be satisfied by a material, product, or service. ...
.

The following examples illustrate a few specifications that could be expressed in a regular expression:

  • the sequence of characters "car" in any context, such as "car", "cartoon", or "bicarbonate"
  • the word "car" when it appears as an isolated word
  • the word "car" when preceded by the word "blue" or "red"
  • a dollar sign immediately followed by one or more digits, and then optionally a period and exactly two more digits


Regular expressions can be much more complex than these examples.

Regular expressions are used by many text editor
Text editor

A text editor is a type of software application used for editing plain text files.Text editors are often provided with operating systems or software development packages, and can be used to change configuration files and programming language source code....
s, utilities, and programming languages to search and manipulate text based on pattern
Pattern

A pattern, from the French language patron, is a type of theme of recurring events of or objects, sometimes referred to as elements of a set....
s. For example, Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
, Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
 and Tcl
Tcl

Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration"?according to the author?with programmers devising their own languages intended to be embedded into applications, Tcl quickly gained wide acceptance on its own and is generally thought to be easy to learn, but powerful in competent hands....
 have a powerful regular expression engine built directly into their syntax. Several utilities provided by Unix
Unix

Unix is a computer operating system originally developed in 1969 by a group of American Telephone & Telegraph employees at Bell Labs, including Ken Thompson , Dennis Ritchie, Douglas McIlroy, and Joe Ossanna....
 distributions—including the editor ed
Ed (text editor)

ed is a standard text editor on the Unix operating system. ed was originally written by Ken Thompson and contains one of the first implementations of regular expressions....
 and the filter grep
Grep

grep is a command line interface text search utility originally written for Unix. The name is taken from the first letters in global / regular expression / print, a series of instructions for the ed text editor....
—were the first to popularize the concept of regular expressions.

As an example of the syntax, the regular expression \bex can be used to search for all instances of the string "ex" that occur after 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 a word and not immediately after a word boundary).

Many modern computing systems provide wildcard character
Wildcard character

The term wildcard character has the following meanings:...
s in matching filenames from a file system
File system

In computing, a file system is a method for store and organize computer files and the data they contain to make it easy to find and access them....
. This is a core capability of many command-line shells
Shell (computing)

In computing, a shell is a piece of software that provides an Interface for users. Typically, the term refers to an operating system shell which provides access to the services of a kernel ....
 and is also known as globbing. Wildcards differ from regular expressions in that they generally only express very limited forms of alternatives.

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
Set (computer science)

In computer science, a set is a collection of certain values, without any particular Canonical order, and no repeated values. It corresponds with a finite set in mathematics....
, without having to list all elements
Data element

In metadata, the term data element is an atomic unit of data that has precise meaning or precise semantics. A data element has:# An identification such as a data element name...
. 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.

Boolean "or"
A vertical bar
Vertical bar

The vertical bar has various names including the pipe , verti-bar, vbar, stick, vertical line, vertical slash, think colon, or divider line by others....
 separates alternatives. For example, gray|grey can match "gray" or "grey".
Grouping
Parentheses
Bracket

Brackets are punctuation marks used in pairs to set apart or interject text within other text. In computer science, the term is sometimes said to strictly apply to the square or box type....
 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 the question mark
Question mark

The question mark , also known as an interrogation point, question point, query, or eroteme, is a punctuation that replaces the Full stop at the end of an interrogative sentence....
 ?, the asterisk
Asterisk

An 'asterisk' is a typographical symbol or glyph. It is so called because it resembles a conventional image of a star. Computer scientists and mathematicians often pronounce it as star ....
 * (derived from the Kleene star
Kleene star

In mathematical logic and computer science, the Kleene star is a unary operation, either on Set of string or on sets of symbols or characters....
), and the plus sign +.
?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
Syntax

In linguistics, syntax is the study of the principles and rules for constructing Sentence s in natural languages. In addition to referring to the discipline, the term syntax is also used to refer directly to the rules and principles that govern the sentence structure of any individual language, as in "the Irish syntax"....
 for regular expressions varies among tools and with context; more detail is given in the Syntax section.

History

The origins of regular expressions lie in automata theory
Automata theory

In theoretical computer science, automata theory is the study of abstract machines and problems which they are able to solve. Automata theory is closely related to formal language theory as the automata are often classified by the class of formal languages they are able to recognize....
 and formal language theory
Formal language

A formal language is a set of words, i.e. finite string of letters, or symbols. The inventory from which these letters are taken is called the alphabet over which the language is defined....
, both of which are part of theoretical computer science
Theoretical computer science

Theoretical computer science is the collection of topics of computer science that focuses on the more abstract, logical and mathematical aspects of computing, such as the theory of computation, analysis of algorithms, and semantics of programming languages....
. These fields study models of computation (automata) and ways to describe and classify formal languages. In the 1950s, mathematician Stephen Cole Kleene
Stephen Cole Kleene

Stephen Cole Kleene was an United States mathematician who helped lay the foundations for theoretical computer science. One of many distinguished students of Alonzo Church, Kleene, along with Alan Turing, Emil Post, and others, is best known as a founder of the branch of mathematical logic known as recursion theory....
 described these models using his mathematical notation called regular sets. The SNOBOL
SNOBOL

SNOBOL 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....
 language was an early implementation of pattern matching
Pattern matching

In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. In contrast to pattern recognition, the pattern is rigidly specified....
, but not identical to regular expressions. Ken Thompson
Ken Thompson

Kenneth Lane Thompson , commonly referred to as Ken Thompson , is an American pioneer of computer science notable for his work with the B and his shepherding of the Unix and Plan 9 from Bell Labs operating systems....
 built Kleene's notation into the editor QED
QED (text editor)

QED is a line-oriented computer text editor that was developed by Butler Lampson and L. Peter Deutsch for the Berkeley Timesharing System running on the SDS 940....
 as a means to match patterns in text files. He later added this capability to the Unix editor ed
Ed (text editor)

ed is a standard text editor on the Unix operating system. ed was originally written by Ken Thompson and contains one of the first implementations of regular expressions....
, which eventually led to the popular search tool grep
Grep

grep is a command line interface text search utility originally written for Unix. The name is taken from the first letters in global / regular expression / print, a series of instructions for the ed text editor....
'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
Expr

expr is a command line interface Unix utility which evaluates an expression and outputs the corresponding value.Syntax: expr expr evaluates integer or String expressions, including pattern matching regular expressions....
, AWK
AWK (programming language)

AWK is a programming language that is designed for processing text-based data, either in files or data streams, and was created at Bell Labs in the 1970s....
, Emacs
Emacs

Emacs is a class of feature-rich text editors, usually characterized by their extensibility. Emacs has, perhaps, more editing commands than any other editor or word processor, numbering over 1,000....
, vi
Vi

vi is a family of screen-oriented text editors which share common characteristics, such as methods of invocation from the operating system command interpreter, and characteristic user interface features....
, and lex
Lex programming tool

In computer science, lex is a Computer program that generates lexical analysiss . Lex is commonly used with the yacc parser generator. Lex, originally written by Eric Schmidt and Mike Lesk, is the standard lexical analyzer generator on many Unix systems, and a tool exhibiting its behavior is specified as part of the POSIX standard....
.

Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
 and Tcl
Tcl

Tcl is a scripting language created by John Ousterhout. Originally "born out of frustration"?according to the author?with programmers devising their own languages intended to be embedded into applications, Tcl quickly gained wide acceptance on its own and is generally thought to be easy to learn, but powerful in competent hands....
 regular expressions were derived from a regex library written by Henry Spencer
Henry Spencer

Henry Spencer is a Canada computer programmer and space enthusiast. He wrote 'regex', a widely-used Library for regular expressions, and co-wrote C News, a Usenet server program....
, though Perl later expanded on Spencer's library to add many new features. Philip Hazel
Philip Hazel

Philip Hazel is a computer programmer best known for writing the Exim mail transport agent and the PCRE regular expression library. He was employed by the University of Cambridge Computing Service until he retired at the end of September 2007....
 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
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 and Apache HTTP Server
Apache HTTP Server

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....
. Part of the effort in the design of Perl 6
Perl 6

Perl 6 is a planned major revision to the Perl programming language. It is a language specification which introduces elements of many modern and historical languages....
 is to improve Perl's regular expression integration, and to increase their scope and capabilities to allow the definition of parsing expression grammar
Parsing expression grammar

A parsing expression grammar, or PEG, is a type of analytic grammar formal grammar that describes a formal language in terms of a set of rules for recognizing string in the language....
s. The result is a mini-language called Perl 6 rules
Perl 6 rules

Perl 6 rules are Perl 6's regular expression, pattern matching and general-purpose parsing facility, and are a core part of the language. Since Perl's pattern-matching constructs have exceeded the capabilities of Formal language regular expressions for some time, Perl 6 documentation will exclusively refer to them as regexes, distancing t...
, 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
Backus–Naur form

In computer science, Backus?Naur Form is a metasyntax used to express context-free grammars: that is, a formal way to describe formal languages....
-style definition of a recursive descent parser
Recursive descent parser

A recursive descent parser is a top-down parsing built from a set of Mutual recursion procedures where each such procedure usually implements one of the production rules of the formal grammar....
 via sub-rules.

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
Standard Generalized Markup Language

The Standard Generalized Markup Language is an International Organization for Standardization Standard metalanguage in which one can define markup languages for documents....
 (precursored by ANSI "GCA 101-1983") consolidated. The kernel of the structure specification language
XML Schema

XML Schema, published as a W3C recommendation in May 2001, is one of several XML schema. It was the first separate schema language for XML to achieve Recommendation status by the W3C....
 standards are regular expressions. Simple use is evident in the DTD
Document Type Definition

Document Type Definition 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....
 element group syntax.

See also Pattern matching: History
Pattern matching

In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. In contrast to pattern recognition, the pattern is rigidly specified....
.

Formal language theory

Regular expressions can be expressed in terms of formal language theory
Formal language

A formal language is a set of words, i.e. finite string of letters, or symbols. The inventory from which these letters are taken is called the alphabet over which the language is defined....
. Regular expressions consist of constants and operators that denote sets of strings and operations over these sets, respectively. Given a finite alphabet S the following constants are defined:
  • (empty set) denoting the set
  • (empty string) e denoting a string with no characters.
  • (literal character
    String literal

    A string literal is the representation of a String value within the source code of a computer program. There are numerous alternate notations for specifying string literals, and the exact notation depends on the individual programming language in question....
    ) a in S denoting a character in the language.


The following operations are defined:
  • (concatenation) RS denoting the set . For example = .
  • (alternation) R|S denoting the set union of R and S. Many textbooks use the symbols , , or for alternation instead of the vertical bar. For example =
  • (Kleene star
    Kleene star

    In mathematical logic and computer science, the Kleene star is a unary operation, either on Set of string or on sets of symbols or characters....
    ) R* denoting the smallest superset
    Subset

    In mathematics, especially in set theory, a Set A is a subset of a set B if A is "contained" inside B. Notice that A and B may coincide....
     of R that contains e and is closed
    Closure (mathematics)

    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. For example, the real numbers are closed under subtraction, but the natural numbers are not: 3 and 7 are both natural numbers, but the result of 3 − 7 is not....
     under string concatenation. This is the set of all strings that can be made by concatenating zero or more strings in R. For example, * = .


The above constants and operators form a Kleene algebra
Kleene algebra

In mathematics, a Kleene algebra is either of two different things:* A bounded lattice distributive lattice with an involution satisfying De Morgan's laws, and the inequality x?−x = y?−y....
.

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)* denotes the set of all strings with no symbols other than a and b, including the empty string:
  • ab*(c|e) 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|e). Sometimes the complement operator ~ is added; ~R denotes the set of all strings over S* 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 language
Regular language

In theoretical computer science, a regular language is a formal language that satisfies the following equivalent properties:* it can be accepted by a deterministic finite state machine...
s, exactly the class of languages accepted by finite state automata
Finite state machine

A finite state machine or finite state automaton or simply a state machine, is a model of behavior composed of a finite number of state s, transitions between those states, and actions....
. There is, however, a significant difference in compactness. Some classes of regular languages can only be described by automata that grow exponentially
Exponential growth

Exponential growth occurs when the growth rate of a mathematical function is proportionality to the function's current value. In the case of a discrete domain of definition with equal intervals it is also called geometric growth or geometric decay ....
 in size, while the length of the required regular expressions only grow linearly. Regular expressions correspond to the type-3 grammars
Formal grammar

In formal language theory, grammars, also called formal grammars or generative grammars, are a formalism used to describe formal languages – i.e....
 of the Chomsky hierarchy
Chomsky hierarchy

Within the field of computer science, specifically in the area of formal languages, the Chomsky hierarchy is a containment hierarchy of classes of formal grammars....
. On the other hand, there is a simple mapping from regular expressions to nondeterministic finite automata
Nondeterministic finite state machine

In the theory of computation, a nondeterministic finite state machine or nondeterministic finite automaton is a finite state machine where for each pair of state and input symbol there may be several possible next states....
 (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 examples show, different regular expressions can express the same language: the formalism is redundant.

It is possible to write an algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
 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
Isomorphism

In abstract algebra, an isomorphism is a bijection map f such that both f and its inverse function f −1 are homomorphisms, i.e., structure-preserving mappings....
 (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
Kleene star

In mathematical logic and computer science, the Kleene star is a unary operation, either on Set of string or on sets of symbols or characters....
 and set union
Union (set theory)

In set theory, the term Union refers to a set operation used in the convergence of set elements to form a resultant set containing the elements of both sets....
 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
Star height problem

The star-height problem in formal language theory is the question whether all regular languages can be expressed using Regular_expression#Formal_language_theorys of limited star height, i....
. Recently, Cornell University professor Dexter Kozen axiomatized regular expressions with Kleene algebra
Kleene algebra

In mathematics, a Kleene algebra is either of two different things:* A bounded lattice distributive lattice with an involution satisfying De Morgan's 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


POSIX


POSIX Basic Regular Expressions

Traditional Unix
Unix

Unix is a computer operating system originally developed in 1969 by a group of American Telephone & Telegraph employees at Bell Labs, including Ken Thompson , Dennis Ritchie, Douglas McIlroy, and Joe Ossanna....
 regular expression syntax followed common conventions but often differed from tool to tool. The IEEE
Institute of Electrical and Electronics Engineers

The Institute of Electrical and Electronics Engineers or IEEE is an international non-profit, professional body for the advancement of technology related to electricity....
 POSIX
POSIX

POSIX or "Portable Operating System Interface" is the collective name of a family of related standardizations specified by the Institute of Electrical and Electronics Engineers to define the application programming interface , along with shell and utilities interfaces for software compatible with variants of the Unix operating system, altho...
 Basic Regular Expressions (BRE) standard (released alongside an alternative flavor called Extended Regular Expressions or ERE) was designed mostly for backward compatibility with the traditional (Simple Regular Expression) syntax but provided a common standard which has since been adopted as the default syntax of many Unix regular expression tools, though there is often some variation or additional features. Many such tools also provide support for ERE syntax with command line argument
Command line argument

In computer command line interfaces, a command line argument is an Parameter sent to a program being called. In general, a program can take any number of command line arguments, which may be necessary for the program to run, or may even be ignored, depending on the function of that program....
s.

In the BRE syntax, most characters are treated as literal
Literal

Literal may refer to:*Literal and figurative language, taken in a non-figurative sense.*Literal translation, the close adherence to the forms of a source language text....
s — they match only themselves (i.e., a matches "a"). The exceptions, listed below, are called metacharacter
Metacharacter

A metacharacter is a character that has a special meaning to a computer program, such as a Operating system shell or a regular expression engine....
s or metasequences.

Metacharacter Description
.Matches any single character (many applications exclude newline
Newline

In computing, a newline is a special character or sequence of characters signifying the end of a line of text. The name comes from the fact that the next character after the newline will appear on a new line?that is, on the next line below the text, immediately proceeding the newline....
s, and exactly which characters are considered newlines is flavor, character encoding, and platform specific, but it is safe to assume that the line feed character is included). Within POSIX bracket expressions, the dot character matches a literal dot. For example, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c".
[ ]A bracket expression. 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", or "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].
[^ ]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 line-based tools, it matches the starting position of any line.
$Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, 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.
\nMatches 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 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.
Matches the preceding element at least m and not more than n times. For example, a\ matches only "aaa", "aaaa", and "aaaaa". This is not found in a few, older instances of regular expressions.


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
The meaning of metacharacters escaped
Escape sequence

An escape sequence is a series of character used to change the state of computers and their attached peripheral devices. These are also known as control sequences, reflecting their use in device control....
 with a backslash is reversed for some characters in the POSIX Extended Regular Expression (ERE) syntax. With this syntax, a backslash causes the metacharacter to be treated as a literal character. So, for example, \( \) is now ( ) and \ is now . Additionally, support is removed for \n backreferences and the following metacharacters are added:

Metacharacter Description
?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.
>abc>def matches "abc" or "def".


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".


POSIX Extended Regular Expressions can often be used with modern Unix utilities by including the command line flag -E.

POSIX character classes
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 Perl ASCII Description
[:alnum:]  [A-Za-z0-9] Alphanumeric characters
[:word:] \w [A-Za-z0-9_] Alphanumeric characters plus "_"
  \W [^\w] non-word character
[:alpha:]  [A-Za-z] Alphabetic characters
[:blank:]  [ \t] Space and tab
[:cntrl:]  [\x00-\x1F\x7F] Control characters
[:digit:] \d [0-9] Digits
  \D [^\d] non-digit
[:graph:]  [\x21-\x7E] Visible characters
[:lower:]  [a-z] Lowercase letters
[:print:]  [\x20-\x7E] Visible characters and spaces
[:punct:]  [-!"#$%&'*+,./:;<=>?@[\\\]_`
Punctuation characters
[:space:] \s [ \t\r\n\v\f] Whitespace characters
\S [^\s] non-whitespace character
[:upper:]  [A-Z] Uppercase letters
[:xdigit:]  [A-Fa-f0-9] Hexadecimal digits
> POSIX character classes can only be used within bracket expressions. 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
Vim (text editor)

Vim is a text editor first released by Bram Moolenaar in 1991 for the Amiga computer. The name "Vim" is an acronym for "Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code....
 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.

Note that what the POSIX regular expression standards call character classes are commonly referred to as POSIX character classes in other regular expression flavors which support them. With most other regular expression flavors, the term character class is used to describe what POSIX calls bracket expressions.

Perl-derivative regular expressions

Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
 has a more consistent and richer syntax than the POSIX basic (BRE) and extended (ERE) regular expression standards. An example of its consistency is that \ always escapes a non-alphanumeric character. Another example of functionality possible with Perl but not POSIX-compliant regular expressions is the concept of lazy quantification (see the next section).

Due largely to its expressive power, many other utilities and programming languages have adopted syntax similar to Perl's — for example, Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
, JavaScript
JavaScript

JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
, PCRE, Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
, Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
, Microsoft
Microsoft

Microsoft Corporation is a multinational corporation computer technology corporation that develops, manufactures, licenses, and supports a wide range of computer software products for computing devices....
's .NET Framework
.NET Framework

The Microsoft .NET Framework is a software framework that is available with several Microsoft Windows operating systems. It includes a large Library of coded solutions to prevent common programming problems and a virtual machine that manages the execution of programs written specifically for the Software framework....
, and the W3C's
World Wide Web Consortium

The World Wide Web Consortium is the main international standards organization for the World Wide Web . It is arranged as a consortium where member organizations maintain full-time staff for the purpose of working together in the development of standards for the World Wide Web....
 XML Schema all use regular expression syntax similar to Perl's. Some languages and tools such as PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 support multiple regular expression flavors. Perl-derivative regular expression implementations are not identical, and many implement only a subset of Perl's features. With Perl 5.10, this process has come full circle with Perl incorporating syntax extensions originally from Python, PCRE, the .NET Framework, and Java.

Simple Regular Expressions


Simple Regular Expressions is a syntax that may be used by historical versions of application programs, and may be supported within some applications for the purpose of providing backward compatibility, These forms of regular expression syntax are considered to be deprecated and should not be used.

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 , <2004>.

...would likely come up with the pattern <.*>, or similar. However, this pattern will actually return ", <2004>" instead of the "" 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

Backtracking is a general algorithm for finding all solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c as soon as it determines that c cannot possibly be completed to a valid solution ....
.

Patterns for non-regular languages

Many features found in modern regular expression libraries provide an expressive power that far exceeds the regular language
Regular language

In theoretical computer science, a regular language is a formal language that satisfies the following equivalent properties:* it can be accepted by a deterministic finite state machine...
s. 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
Context-free language

In formal language theory, a context-free language is a formal language generated by some context-free grammar. The set of all context-free languages is identical to the set of languages accepted by pushdown automaton....
. Pattern matching
Pattern matching

In computer science, pattern matching is the act of checking for the presence of the constituents of a given pattern. In contrast to pattern recognition, the pattern is rigidly specified....
 with an unbounded number of back references, as supported by numerous modern tools, is NP-hard
NP-hard

NP-hard , in computational complexity theory, is a class of problems informally "at least as hard as the hardest problems in NP ." A problem H is NP-hard if and only if there is an NP-complete problem L that is polynomial-time Turing reduction to H, i.e....
.

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
Formal language

A formal language is a set of words, i.e. finite string of letters, or symbols. The inventory from which these letters are taken is called the alphabet over which the language is defined....
 and pattern matching. For this reason, some people have taken to using the term regex or simply pattern to describe the latter. Larry Wall
Larry Wall

Larry Wall is a programmer and author, most widely known for his creation of the Perl programming language in 1987....
 (author of Perl) writes in Apocalypse 5:

Implementations and running times

There are at least three essentially different algorithm
Algorithm

In mathematics, computing, linguistics and related subjects, an algorithm is a sequence of finite instructions, often used for calculation and data processing....
s that decide if and how a given regular expression matches a string.

The oldest and fastest two rely on a result in formal language theory that allows every nondeterministic finite state machine
Nondeterministic finite state machine

In the theory of computation, a nondeterministic finite state machine or nondeterministic finite automaton is a finite state machine where for each pair of state and input symbol there may be several possible next states....
 (NFA) to be transformed into a deterministic finite state machine
Deterministic finite state machine

In the theory of computation, a deterministic automaton finite state machine 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....
 (DFA). The DFA can be constructed explicitly and then run on the resulting input string one symbol at a time. Constructing the DFA for a regular expression of size m has the time and memory cost of O
Big O notation

In mathematics, big O notation describes the asymptotic analysis of a function when the argument tends towards a particular value or infinity, usually in terms of simpler functions....
(2m), but it can be run on a string of size n in time O(n). An alternative approach is to simulate the NFA directly, essentially building each DFA state on demand and then discarding it at the next step, possibly with caching. This keeps the DFA implicit and avoids the exponential construction cost, but running cost rises to O(nm). The explicit approach is called the DFA algorithm and the implicit approach the NFA algorithm. As both can be seen as different ways of executing the same DFA, they are also often called the DFA algorithm without making a distinction. These algorithms are 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.

The third algorithm is to match the pattern against the input string by backtracking
Backtracking

Backtracking is a general algorithm for finding all solutions to some computational problem, that incrementally builds candidates to the solutions, and abandons each partial candidate c as soon as it determines that c cannot possibly be completed to a valid solution ....
. 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 exponentially increasing number of sub-cases. More complex implementations will often identify and speed up or abort common cases where they would otherwise run slowly.

Although backtracking implementations only 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 extensions 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
Unicode

Unicode is a computing industry standard allowing computers to consistently represent and manipulate Character expressed in most of the world's writing systems....
. In most respects it makes no difference what the character set is, but some issues do arise when extending regular expressions to support Unicode.

  • Supported encoding. Some regular expression libraries expect the UTF-8
    UTF-8

    UTF-8 is a Variable-width encoding character encoding for Unicode. It is able to represent any character in the Unicode standard, yet the initial encoding of byte codes and character assignments for UTF-8 is backward compatibility with ASCII....
     encoding, while others might expect UTF-16, or UTF-32.


  • Supported Unicode range. Many regular expression engines support only the Basic Multilingual Plane
    Mapping of Unicode characters

    Unicode?s Universal Character Set has a potential capacity to support over 1 million characters. Each UCS character is mapped to a code point which is an integer between 0 and 1,114,111 used to represent each character within the internal logic of text processing software ....
    , 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.


  • Extending ASCII-oriented constructs 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
    Vim (text editor)

    Vim is a text editor first released by Bram Moolenaar in 1991 for the Amiga computer. The name "Vim" is an acronym for "Vi IMproved" because Vim was created as an extended version of the vi editor, with many additional features designed to be helpful in editing program source code....
     editor, allow block-crossing but limit the number of characters in a range to 128.


  • Case insensitivity. Some case-insensitivity 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.


  • Cousins of case insensitivity. As the English alphabet has case distinction, case insensitivity became a logical feature in text searching. Unicode introduced alphabetic scripts without case like Devanagari
    Devanagari

    , or 'Nagari', is an abugida alphabet of India and Nepal. It is written from left to right, lacks distinct letter cases, and is recognizable by a distinctive horizontal line running along the tops of the letters that links them together....
    . For these, case sensitivity is not applicable. For scripts like Chinese, another distinction seems logical: between traditional and simplified. In Arabic scripts, insensitivity to initial, medial, final and isolated position may be desired.


  • Normalization. Unicode introduced combining characters. Like old typewriters, plain letters can be followed by non-spacing accent symbols to form a single accented letter. As a consequence, two different code sequences can result in identical character display.


  • New control codes. Unicode introduced amongst others, byte order marks and text direction markers. These codes might have to be dealt with in a special way.


  • Introduction of character classes for Unicode blocks and Unicode general character properties. In Perl
    Perl

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
     and the library, classes of the form \p match characters in block X and \P match the opposite. Similarly, \p matches any character in the Armenian block, and \p matches any character with the general character property X. For example, \p matches any upper-case letter.


Uses of regular expressions

Regular expressions are useful in the production of syntax highlighting
Syntax highlighting

Syntax highlighting is a feature of some text editors that displays text—especially source code—in different colors and typefaces according to the category of terms....
 systems, data validation
Data validation

In computer science, data validation is the process of ensuring that a program operates on clean, correct and useful data. It uses routines, often called "validation rules" or "check routines", that check for correctness, meaningfulness, and security of data that are input to the system....
, and many other tasks.

While regular expressions would be useful on search engines such as Google
Google

Google Inc. is an United States public company, earning revenue from AdWords related to its Google search, Gmail, Google Maps, Google Apps, Orkut, and YouTube services as well as selling advertising-free versions of the Google Search Appliance....
 or Live Search, processing them across the entire database could consume excessive computer 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
Google Code Search

Google Code Search is a free Development stage#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

  • Comparison of regular expression engines
    Comparison of regular expression engines

    Libraries formerly called Regex++ included since version 2.13.0 C++ bindings were developed by Google and became officially part of PCRE in 2006...
  • Extended Backus–Naur form
    Extended Backus–Naur form

    In computer science, Extended Backus?Naur Form is a metasyntax notation used to express context-free grammars: that is, a formal way to describe computer programming languages and other formal languages....
  • List of regular expression software
    List of regular expression software

    The following is a list of software applications that use regular expressions. In some cases, only later versions of the applications use regular expressions....
  • Regular expression examples
  • Regular tree grammar
    Regular tree grammar

    In Computer Science, a regular tree grammar is a formal grammar that allows trees to be generated....
  • Regular language
    Regular language

    In theoretical computer science, a regular language is a formal language that satisfies the following equivalent properties:* it can be accepted by a deterministic finite state machine...


External links


  • at the Mozilla Developer Center
    Mozilla Developer Center

    Mozilla Developer Center , started in early 2005, is the official Mozilla Foundation website for development documentation and news about Firefox, Mozilla Thunderbird, and other Mozilla Foundation projects....
  •  — tutorial and reference which covers many popular regex flavors