thumb|upright=1.5|
A regular expression (shortened as regex or regexp), sometimes referred to as a rational expression, is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. Regular expression techniques are developed in theoretical computer science and formal language theory.
The concept of regular expressions began in the 1950s, when the American mathematician Stephen Cole Kleene formalized the concept of a regular language. They came into common use with Unix text-processing utilities. Different syntaxes for writing regular expressions have existed since the 1980s, one being the POSIX standard and another, widely used, being the Perl syntax.
Regular expressions are used in search engines, in search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK, and in lexical analysis. Regular expressions are supported in many programming languages. Library implementations are often called an "engine", and many of these are available for reuse.
History
thumb|upright|[[Stephen Cole Kleene, who introduced the concept]]
Regular expressions originated in 1951, when mathematician Stephen Cole Kleene described regular languages using his mathematical notation called regular events. These arose in theoretical computer science, in the subfields of automata theory (models of computation) and the description and classification of formal languages, motivated by Kleene's attempt to describe early artificial neural networks. (Kleene introduced it as an alternative to McCulloch & Pitts's "prehensible", but admitted "We would welcome any suggestions as to a more descriptive term.") Other early implementations of pattern matching include the SNOBOL language, which did not use regular expressions, but instead its own pattern matching constructs.
Regular expressions entered popular use from 1968 in two uses: pattern matching in a text editor and lexical analysis in a compiler. Among the first appearances of regular expressions in program form was when Ken Thompson built Kleene's notation into the editor QED as a means to match patterns in text files. For speed, Thompson implemented regular expression matching by just-in-time compilation (JIT) to IBM 7094 code on the Compatible Time-Sharing System, an important early example of JIT compilation. 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: <code>g/re/p</code> meaning "Global search for Regular Expression and Print matching lines"). Around the same time that Thompson developed QED, a group of researchers including Douglas T. Ross implemented a tool based on regular expressions that is used for lexical analysis in compiler design.
Many variations of these original forms of regular expressions were used in Unix programs at Bell Labs in the 1970s, including lex, sed, AWK, and expr, and in other programs such as vi, and Emacs (which has its own, incompatible syntax and behavior). Regexes were subsequently adopted by a wide range of programs, with these early forms standardized in the POSIX.2 standard in 1992.
In the 1980s, the more complicated regexes arose in Perl, which originally derived from a regex library written by Henry Spencer (1986), who later wrote an implementation for Tcl called Advanced Regular Expressions. The Tcl library is a hybrid NFA/DFA implementation with improved performance characteristics. Software projects that have adopted Spencer's Tcl regular expression implementation include PostgreSQL. Perl later expanded on Spencer's original library to add many new features. Part of the effort in the design of Raku (formerly named Perl 6) is to improve Perl's regex integration, and to increase their scope and capabilities to allow the definition of parsing expression grammars. The result is a mini-language called Raku rules, which are used to define Raku grammar as well as provide a tool to programmers in the language. These rules maintain existing features of Perl 5.x regexes, but also allow BNF-style definition of a recursive descent parser via sub-rules.
The use of regexes 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 consists of regexes. Its use is evident in the DTD element group syntax. Prior to the use of regular expressions, many search languages allowed simple wildcards, for example "*" to match any sequence of characters, and "?" to match a single character. Relics of this can be found today in the glob syntax for filenames, and in the SQL <code>LIKE</code> operator.
Starting in 1997, Philip Hazel developed PCRE (Perl Compatible Regular Expressions), which attempts to closely mimic Perl's regex functionality and is used by many modern tools including PHP and Apache HTTP Server.
Today, regexes are widely supported in programming languages, text processing programs (particularly lexers), advanced text editors, and some other programs. Regex support is part of the standard library of many programming languages, including Java and Python, and is built into the syntax of others, including Perl and ECMAScript. In the late 2010s, several companies started to offer hardware, FPGA, GPU implementations of PCRE compatible regex engines that are faster compared to CPU implementations.
Patterns
The phrase regular expressions, or regexes, is often used to mean the specific, standard textual syntax for representing patterns for matching text, as distinct from the mathematical notation described below. Each character in a regular expression (that is, each character in the string describing its pattern) is either a metacharacter, having a special meaning, or a regular character that has a literal meaning. For example, in the regex <code>b.</code>, 'b' is a literal character that matches just 'b', while '.' is a metacharacter that matches every character except a newline. Therefore, this regex matches, for example, 'b%', or 'bx', or 'b5'. Together, metacharacters and literal characters can be used to identify text of a given pattern or process a number of instances of it. Pattern matches may vary from a precise equality to a very general similarity, as controlled by the metacharacters. For example, <code>.</code> is a very general pattern, <code><nowiki>[a-z]</nowiki></code> (match all lowercase letters from 'a' to 'z') is less general and <code>b</code> is a precise pattern (matches just 'b'). The metacharacter syntax is designed specifically to represent prescribed targets in a concise and flexible way to direct the automation of text processing of a variety of input data, in a form easy to type using a standard ASCII keyboard.
A very simple case of a regular expression in this syntax is to locate a word spelled two different ways in a text editor; for example, the regular expression <code>seriali[sz]e</code> matches both "serialise" and "serialize". Wildcard characters also achieve this, but are more limited in what they can pattern, as they have fewer metacharacters and a simple language-base.
The usual context of wildcard characters is in globbing similar names in a list of files, whereas regexes are usually employed in applications that pattern-match text strings in general. For example, the regex <syntaxhighlight lang="ragel" inline>^[ \t]+|[ \t]+$</syntaxhighlight> matches excess whitespace at the beginning or end of a line. An advanced regular expression that matches any numeral is <syntaxhighlight lang="ragel" inline>[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?</syntaxhighlight>.
right|thumb|[[Thompson's construction algorithm|Translating the Kleene star<br/>(s* means "zero or more of s")]]
A regex processor translates a regular expression in the above syntax into an internal representation that can be executed and matched against a string representing the text being searched in. One possible approach is the Thompson's construction algorithm to construct a nondeterministic finite automaton (NFA), which is then made deterministic and the resulting deterministic finite automaton (DFA) is run on the target text string to recognize substrings that match the regular expression.
The picture shows the NFA scheme <code>N(s*)</code> obtained from the regular expression <code>s*</code>, where s denotes a simpler regular expression in turn, which has already been recursively translated to the NFA N(s).
Basic concepts
A regular expression, often called a pattern, specifies a set of strings required for a particular purpose. A simple way to specify a finite set of strings is to list its elements or members. However, there are often more concise ways: for example, the set containing the three strings "Handel", "Händel", and "Haendel" can be specified by the pattern <code>H(ä|ae?)ndel</code>; we say that this pattern matches each of the three strings. However, there can be many ways to write a regular expression for the same set of strings: for example, <code>(Hän|Han|Haen)del</code> also specifies the same set of three strings in this example.
Most formalisms provide the following operations to construct regular expressions.
; Boolean "or" :
: A vertical bar separates alternatives. For example, can match "gray" or "grey".
; Grouping
: Parentheses are used to define the scope and precedence of the operators (among other uses). For example, <code>gray|grey</code> and are equivalent patterns which both describe the set of "gray" or "grey".
; Quantification
: A quantifier after an element (such as a token, character, or group) specifies how many times the preceding element is allowed to repeat. The most common quantifiers are the question mark <code>?</code>, the asterisk <code>*</code> (derived from the Kleene star), and the plus sign <code>+</code> (Kleene plus).
: {|
|-
| style="width:15px; vertical-align:top;" |<code>?</code>
|The question mark indicates zero or one occurrences of the preceding element. For example, <code><!--DON'T CHANGE THIS TO "colo?r"; REGULAR EXPRESSIONS DON'T WORK LIKE WILDCARDS!-->colou?r</code> matches both "color" and "colour".
|-
| style="vertical-align:top;" |<code><nowiki>*</nowiki></code>
|The asterisk indicates zero or more occurrences of the preceding element. For example, <code>ab*c</code> matches "ac", "abc", "abbc", "abbbc", and so on.
|-
| style="vertical-align:top;" |<code>+</code>
|The plus sign indicates one or more occurrences of the preceding element. For example, <code>ab+c</code> matches "abc", "abbc", "abbbc", and so on, but not "ac".
|-
|<code>{n}</code>
| The preceding item is matched exactly n times.
|-
|<code>{min,}</code> Given a finite alphabet Σ, the following constants are defined
as regular expressions:
- (empty set) ∅ denoting the set ∅.
- (empty string) ε denoting the set containing only the "empty" string, which has no characters at all.
- (literal character) <code>a</code> in Σ denoting the set containing only the character a.
Given regular expressions R and S, the following operations over them are defined
to produce regular expressions:
- (concatenation) <code>(RS)</code> denotes the set of strings that can be obtained by concatenating a string accepted by R and a string accepted by S (in that order). For example, let R denote {"ab", "c"} and S denote {"d", "ef"}. Then, <code>(RS)</code> denotes {"abd", "abef", "cd", "cef"}.
- (alternation) <code>(R|S)</code> denotes the set union of sets described by R and S. For example, if R describes {"ab", "c"} and S describes {"ab", "d", "ef"}, expression <code>(R|S)</code> describes {"ab", "c", "d", "ef"}.
- (Kleene star) <code>(R*)</code> denotes the smallest superset of the set described by R that contains ε and is closed under string concatenation. This is the set of all strings that can be made by concatenating any finite number (including zero) of strings from the set described by R. For example, if R denotes {"0", "1"}, <code>(R*)</code> denotes the set of all finite binary strings (including the empty string). If R denotes {"ab", "c"}, <code>(R*)</code> denotes {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", "abcab", ...}.
To avoid parentheses, it is assumed that the Kleene star has the highest priority followed by concatenation, then alternation. If there is no ambiguity, then parentheses may be omitted. For example, <code>(ab)c</code> can be written as <code>abc</code>, and <code>a|(b(c*))</code> can be written as <code>a|bc*</code>. Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.
Examples:
- <code>a|b*</code> denotes {ε, "a", "b", "bb", "bbb", ...}
- <code>(a|b)*</code> denotes the set of all strings with no symbols other than "a" and "b", including the empty string: {ε, "a", "b", "aa", "ab", "ba", "bb", "aaa", ...}
- <code>ab*(c|ε)</code> denotes the set of strings starting with "a", then zero or more "b"s and finally optionally a "c": {"a", "ac", "ab", "abc", "abb", "abbc", ...}
- <code>(0|(1(01*0)*1))*</code> denotes the set of binary numbers that are multiples of 3: { ε, "0", "00", "11", "000", "011", "110", "0000", "0011", "0110", "1001", "1100", "1111", "00000", ...}
The derivative of a regular expression can be defined using the Brzozowski derivative.
Expressive power and compactness
The formal definition of regular expressions is minimal on purpose, and avoids defining <code>?</code> and <code>+</code>—these can be expressed as follows: <code>a+</code>=<code>aa*</code>, and <code>a?</code>=<code>(a|ε)</code>. Sometimes the complement operator is added, to give a generalized regular expression; here R<sup>c</sup> matches all strings over Σ* that do not match R. In principle, the complement operator is redundant, because it does not grant any more expressive power. However, it can make a regular expression much more concise—eliminating a single complement operator can cause a double exponential blow-up of its length.
Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by deterministic finite automata. There is, however, a significant difference in compactness. Some classes of regular languages can only be described by deterministic finite automata whose size grows exponentially in the size of the shortest equivalent regular expressions. The standard example here is the languages
L<sub>k</sub> consisting of all strings over the alphabet {a,b} whose kth-from-last letter equals a. On the one hand, a regular expression describing L<sub>4</sub> is given by
<math>(a\mid b)^*a(a\mid b)(a\mid b)(a\mid b)</math>.
Generalizing this pattern to L<sub>k</sub> gives the expression:
: <math>(a\mid b)^*a\underbrace{(a\mid b)(a\mid b)\cdots(a\mid b)}_{k-1\text{ times. \, </math>
On the other hand, it is known that every deterministic finite automaton accepting the language L<sub>k</sub> must have at least 2<sup>k</sup> states. Luckily, there is a simple mapping from regular expressions to the more general 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 languages. NFAs are a simple variation of the type-3 grammars of the Chomsky hierarchy.
Given a regular expression, Thompson's construction algorithm computes an equivalent nondeterministic finite automaton. A conversion in the opposite direction is achieved by Kleene's algorithm.
Finally, many real-world "regular expression" engines implement features that cannot be described by the regular expressions in the sense of formal language theory; rather, they implement regexes. See below for more on this.
Deciding equivalence of regular expressions
As seen in many of the examples above, there is more than one way to construct a regular expression to achieve the same results.
It is possible to write an algorithm that, for two given regular expressions, decides whether the described languages are equal; the algorithm reduces each expression to a minimal deterministic finite state machine, and determines whether they are isomorphic (equivalent).
Algebraic laws for regular expressions can be obtained using a method by Gischer which is best explained along an example: In order to check whether (X+Y)<sup>∗</sup> and (X<sup>∗</sup> Y<sup>∗</sup>)<sup>∗</sup> denote the same regular language, for all regular expressions X, Y, it is necessary and sufficient to check whether the particular regular expressions (a+b)<sup>∗</sup> and (a<sup>∗</sup> b<sup>∗</sup>)<sup>∗</sup> denote the same language over the alphabet Σ={a,b}. More generally, an equation E=F between regular-expression terms with variables holds if, and only if, its instantiation with different variables replaced by different symbol constants holds.
Every regular expression can be written solely in terms of the Kleene star and set unions over finite words. This is a surprisingly difficult problem. As simple as the regular expressions are, there is no method to systematically rewrite them to some normal form. The lack of axiom in the past led to the star height problem. In 1991, Dexter Kozen axiomatized regular expressions as a Kleene algebra, using equational and Horn clause axioms.
Already in 1964, Redko had proved that no finite set of purely equational axioms can characterize the algebra of regular languages.
Syntax
<!-- 'Google Codesearch FAQ' links here. -->
A regex pattern matches a target string. The pattern is composed of a sequence of atoms. An atom is a single point within the regex pattern which it tries to match to the target string. The simplest atom is a literal, but grouping parts of the pattern to match an atom will require using <code>( )</code> as metacharacters. Metacharacters help form: atoms; quantifiers telling how many atoms (and whether it is a greedy quantifier or not); a logical OR character, which offers a set of alternatives, and a logical NOT character, which negates an atom's existence; and backreferences to refer to previous atoms of a completing pattern of atoms. A match is made, not when all the atoms of the string are matched, but rather when all the pattern atoms in the regex have matched. The idea is to make a small pattern of characters stand for a large number of possible strings, rather than compiling a large list of all the literal possibilities.
Depending on the regex processor there are about fourteen metacharacters, characters that may or may not have their literal character meaning, depending on context, or whether they are "escaped", i.e. preceded by an escape sequence, in this case, the backslash <code>\</code>. Modern and POSIX extended regexes use metacharacters more often than their literal meaning, so to avoid "backslash-osis" or leaning toothpick syndrome, they have a metacharacter escape to a literal mode; starting out, however, they instead have the four bracketing metacharacters <code>( )</code> and <code>{ }</code> be primarily literal, and "escape" this usual meaning to become metacharacters. Common standards implement both. The usual metacharacters are <code> {}[]()^$.|*+?</code> and <code>\</code>. The usual characters that become metacharacters when escaped are <code>dswDSW</code> and <code>N</code>.
Delimiters
When entering a regex in a programming language, they may be represented as a usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where the regex <code>re</code> is entered as <code>"re"</code>. However, they are often written with slashes as delimiters, as in <code>/re/</code> for the regex <code>re</code>. This originates in ed, where <code>/</code> is the editor command for searching, and an expression <code>/re/</code> can be used to specify a range of lines (matching the pattern), which can be combined with other commands on either side, most famously <code>g/re/p</code> as in grep ("global regex print"), which is included in most Unix-based operating systems, such as Linux distributions. A similar convention is used in sed, where search and replace is given by <code>s/re/replacement/</code> and patterns can be joined with a comma to specify a range of lines as in <code>/re1/,/re2/</code>. This notation is particularly well known due to its use in Perl, where it forms part of the syntax distinct from normal string literals. In some cases, such as sed and Perl, alternative delimiters can be used to avoid collision with contents, and to avoid having to escape occurrences of the delimiter character in the contents. For example, in sed the command <code>s,/,X,</code> will replace a <code>/</code> with an <code>X</code>, using commas as delimiters.
IEEE POSIX Standard <span class="anchor" id="POSIX"></span>
The IEEE POSIX standard has three sets of compliance: BRE (Basic Regular Expressions), ERE (Extended Regular Expressions), and SRE (Simple Regular Expressions). SRE is deprecated, in favor of BRE, as both provide backward compatibility. The subsection below covering the character classes applies to both BRE and ERE.
BRE and ERE work together. ERE adds <code>?</code>, <code>+</code>, and <code>|</code>, and it removes the need to escape the metacharacters <code>( )</code> and <code>{ }</code>, which are required in BRE. Furthermore, as long as the POSIX standard syntax for regexes is adhered to, there can be, and often is, additional syntax to serve specific (yet POSIX compliant) applications. Although POSIX.2 leaves some implementation specifics undefined, BRE and ERE provide a "standard" which has since been adopted as the default syntax of many tools, where the choice of BRE or ERE modes is usually a supported option. For example, GNU <code>grep</code> has the following options: "<code>grep -E</code>" for ERE, and "<code>grep -G</code>" for BRE (the default), and "<code>grep -P</code>" for Perl regexes.
Perl regexes have become a de facto standard, having a rich and powerful set of atomic expressions. Perl has no "basic" or "extended" levels. As in POSIX EREs, <code>( )</code> and <code>{ }</code> are treated as metacharacters unless escaped; other metacharacters are known to be literal or symbolic based on context alone. Additional functionality includes lazy matching, backreferences, named capture groups, and recursive patterns.
POSIX basic and extended
In the POSIX standard, Basic Regular Syntax (BRE) requires that the metacharacters <code>( )</code> and <code>{ }</code> be designated <code>\(\)</code> and <code>\{\}</code>, whereas Extended Regular Syntax (ERE) does not.
{| class="wikitable"
|-
! Metacharacter
! Description
|- valign="top"
!<code>^</code>
|Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
|- valign="top"
!<code>.</code>
|Matches any single character (many applications exclude newlines, 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, <code>a.c</code> matches "abc", etc., but <code>[a.c]</code> matches only "a", ".", or "c".
|- valign="top"
!<code>[ ]</code>
|A bracket expression. Matches a single character that is contained within the brackets. For example, <code>[abc]</code> matches "a", "b", or "c". <code>[a-z]</code> specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: <code>[abcx-z]</code> matches "a", "b", "c", "x", "y", or "z", as does <code>[a-cx-z]</code>.
The <code>-</code> character is treated as a literal character if it is the last or the first (after the <code>^</code>, if present) character within the brackets: <code>[abc-]</code>, <code>[-abc]</code>, <code>[^-abc]</code>. Backslash escapes are not allowed. The <code>]</code> character can be included in a bracket expression if it is the first (after the <code>^</code>, if present) character: <code>[]abc]</code>, <code>[^]abc]</code>.
|- valign="top"
!<code>[^ ]</code>
|Matches a single character that is not contained within the brackets. For example, <code>[^abc]</code> matches any character other than "a", "b", or "c". <code>[^a-z]</code> matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed.
|- valign="top"
!<code>$</code>
|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.
|- valign="top"
!<code>( )</code>
|Defines a marked subexpression, also called a capturing group, which is essential for extracting the desired part of the text (See also the next entry, <code>\n</code>). BRE mode requires .
|- valign="top"
!<code>\n</code>
|Matches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is defined in the POSIX standard. Some tools allow referencing more than nine capturing groups. Also known as a back-reference, this feature is supported in BRE mode.
|- valign="top"
!<code>*</code>
|Matches the preceding element zero or more times. For example, <code>ab*c</code> matches "ac", "abc", "abbbc", etc. <code>[xyz]*</code> matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. <code>(ab)*</code> matches "", "ab", "abab", "ababab", and so on.
|- valign="top"
!
|Matches the preceding element at least m and not more than n times. For example, <code>a{3,5}</code> matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regexes. BRE mode requires <code>}</code>.
|}
Examples:
- <code>.at</code> matches any three-character string ending with "at", including "hat", "cat", "bat", "4at", "#at" and " at" (starting with a space).
- <code>[hc]at</code> matches "hat" and "cat".
- <code>[^b]at</code> matches all strings matched by <code>.at</code> except "bat".
- <code>[^hc]at</code> matches all strings matched by <code>.at</code> other than "hat" and "cat".
- <code>^[hc]at</code> matches "hat" and "cat", but only at the beginning of the string or line.
- <code>[hc]at$</code> matches "hat" and "cat", but only at the end of the string or line.
- <code>\[.\]</code> matches any single character surrounded by "[" and "]" since the brackets are escaped, for example: "[a]", "[b]", "[7]", "[@]", "[]]", and "[ ]" (bracket space bracket).
- <code>s.*</code> matches s followed by zero or more characters, for example: "s", "saw", "seed", "s3w96.7", and "s6#h%(>>>m n mQ".
According to Russ Cox, the POSIX specification requires ambiguous subexpressions to be handled in a way different from Perl's. The committee replaced Perl's rules with one that is simple to explain, but the new "simple" rules are actually more complex to implement: they were incompatible with pre-existing tooling and made it essentially impossible to define a "lazy match" (see below) extension. As a result, very few programs actually implement the POSIX subexpression rules (even when they implement other parts of the POSIX syntax).
Metacharacters in POSIX extended
The meaning of metacharacters escaped 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, <code>\( \)</code> is now <code>( )</code> and <code>\{ \}</code> is now <code>{ }</code>. Additionally, support is removed for <code>\n</code> backreferences and the following metacharacters are added:
{| class="wikitable"
|-
! Metacharacter
! Description
|- valign="top"
! <code>?</code>
| Matches the preceding element zero or one time. For example, <code>ab?c</code> matches only "ac" or "abc".
|-
! <code>+</code>
| Matches the preceding element one or more times. For example, <code>ab+c</code> matches "abc", "abbc", "abbbc", and so on, but not "ac".
|-
! <code><nowiki>|</nowiki></code>
| The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, <code><nowiki>abc|def</nowiki></code> matches "abc" or "def".
|}
Examples:
- <code>[hc]?at</code> matches "at", "hat", and "cat".
- <code>[hc]*at</code> matches "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on.
- <code>[hc]+at</code> matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".
- <code>cat|dog</code> matches "cat" or "dog".
POSIX Extended Regular Expressions can often be used with modern Unix utilities by including the command line flag <var>-E</var>.
Character classes
The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, <syntaxhighlight lang="ragel" inline>[A-Z]</syntaxhighlight> could stand for any uppercase letter in the English alphabet, and <syntaxhighlight lang="ragel" inline>\d</syntaxhighlight> could mean any digit. Character classes apply to both POSIX levels.
When specifying a range of characters, such as <syntaxhighlight lang="ragel" inline>[a-Z]</syntaxhighlight> (i.e. lowercase <syntaxhighlight lang="ragel" inline>a</syntaxhighlight> to uppercase <syntaxhighlight lang="ragel" inline>Z</syntaxhighlight>), the computer's locale settings determine the contents by the numeric ordering of the character encoding. They could store digits in that sequence, or the ordering could be abc...zABC...Z, or aAbBcC...zZ. So the POSIX standard defines a character class, which will be known by the regex processor installed. Those definitions are in the following table:
{| class="wikitable sortable"
|-
! Description
! POSIX !! Perl/Tcl !! Vim !! Java !! ASCII
|-
| ASCII characters
|
|
|
| <syntaxhighlight lang="ragel" inline>\p{ASCII}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[\x00-\x7F]</syntaxhighlight>
|-
| Alphanumeric characters
| <syntaxhighlight lang="ragel" inline>[:alnum:]</syntaxhighlight>
|
|
| <syntaxhighlight lang="ragel" inline>\p{Alnum}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[A-Za-z0-9]</syntaxhighlight>
|-
| Alphanumeric characters plus "_"
|
| <syntaxhighlight lang="ragel" inline>\w</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\w</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\w</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[A-Za-z0-9_]</syntaxhighlight>
|-
| Non-word characters
|
| <syntaxhighlight lang="ragel" inline>\W</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\W</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\W</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[^A-Za-z0-9_]</syntaxhighlight>
|-
| Alphabetic characters
| <syntaxhighlight lang="ragel" inline>[:alpha:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\a</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Alpha}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[A-Za-z]</syntaxhighlight>
|-
| Space and tab
| <syntaxhighlight lang="ragel" inline>[:blank:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\s</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Blank}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[ \t]</syntaxhighlight>
|-
| Word boundaries
|
| <syntaxhighlight lang="ragel" inline>\b</syntaxhighlight>
| <code>\< \></code>
| <syntaxhighlight lang="ragel" inline>\b</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>(?<=\W)(?=\w)|(?<=\w)(?=\W)</syntaxhighlight>
|-
| Non-word boundaries
|
|
|
| <syntaxhighlight lang="ragel" inline>\B</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>(?<=\W)(?=\W)|(?<=\w)(?=\w)</syntaxhighlight>
|-
| Control characters
| <syntaxhighlight lang="ragel" inline>[:cntrl:]</syntaxhighlight>
|
|
| <syntaxhighlight lang="ragel" inline>\p{Cntrl}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[\x00-\x1F\x7F]</syntaxhighlight>
|-
| Digits
| <syntaxhighlight lang="ragel" inline>[:digit:]</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\d</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\d</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Digit}</syntaxhighlight> or <syntaxhighlight lang="ragel" inline>\d</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[0-9]</syntaxhighlight>
|-
| Non-digits
|
| <syntaxhighlight lang="ragel" inline>\D</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\D</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\D</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[^0-9]</syntaxhighlight>
|-
| Visible characters
| <syntaxhighlight lang="ragel" inline>[:graph:]</syntaxhighlight>
|
|
| <syntaxhighlight lang="ragel" inline>\p{Graph}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[\x21-\x7E]</syntaxhighlight>
|-
| Lowercase letters
| <syntaxhighlight lang="ragel" inline>[:lower:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\l</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Lower}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[a-z]</syntaxhighlight>
|-
| Visible characters and the space character
| <syntaxhighlight lang="ragel" inline>[:print:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\p</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Print}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[\x20-\x7E]</syntaxhighlight>
|-
| Punctuation characters
| <syntaxhighlight lang="ragel" inline>[:punct:]</syntaxhighlight>
|
|
| <syntaxhighlight lang="ragel" inline>\p{Punct}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[][!"#$%&'()*+,./:;<=>?@\^_`{|}~-]</syntaxhighlight>
|-
| Whitespace characters
| <syntaxhighlight lang="ragel" inline>[:space:]</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\s</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\_s</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Space}</syntaxhighlight> or <syntaxhighlight lang="ragel" inline>\s</syntaxhighlight>
| <code>[ \t\r\n\v\f]</code>
|-
| Non-whitespace characters
|
| <syntaxhighlight lang="ragel" inline>\S</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\S</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\S</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[^ \t\r\n\v\f]</syntaxhighlight>
|-
| Uppercase letters
| <syntaxhighlight lang="ragel" inline>[:upper:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\u</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{Upper}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[A-Z]</syntaxhighlight>
|-
| Hexadecimal digits
| <syntaxhighlight lang="ragel" inline>[:xdigit:]</syntaxhighlight>
|
| <syntaxhighlight lang="ragel" inline>\x</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>\p{XDigit}</syntaxhighlight>
| <syntaxhighlight lang="ragel" inline>[A-Fa-f0-9]</syntaxhighlight>
|}
POSIX character classes can only be used within bracket expressions. For example, <syntaxhighlight lang="ragel" inline>[[:upper:]ab]</syntaxhighlight> matches the uppercase letters and lowercase "a" and "b".
An additional non-POSIX class understood by some tools is <syntaxhighlight lang="ragel" inline>[:word:]</syntaxhighlight>, which is usually defined as <syntaxhighlight lang="ragel" inline>[:alnum:]</syntaxhighlight> 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 <syntaxhighlight lang="ragel" inline>\w</syntaxhighlight> and <syntaxhighlight lang="ragel" inline>\h</syntaxhighlight>) since in many programming languages the characters that can begin an identifier are not the same as those that can occur in other positions: numbers are generally excluded, so an identifier would look like <syntaxhighlight lang="ragel" inline>\h\w*</syntaxhighlight> or <syntaxhighlight lang="ragel" inline>[[:alpha:]_][[:alnum:]_]*</syntaxhighlight> in POSIX notation.
Note that what the POSIX regex standards call character classes are commonly referred to as POSIX character classes in other regex flavors which support them. With most other regex flavors, the term character class is used to describe what POSIX calls bracket expressions.
Perl and PCRE
Because of its expressive power and (relative) ease of reading, many other utilities and programming languages have adopted syntax similar to Perl's—for example, Java, JavaScript, Julia, Python, Ruby, Qt, Microsoft's .NET Framework, and XML Schema. Some languages and tools such as Boost and PHP support multiple regex flavors. Perl-derivative regex implementations are not identical and usually implement a subset of features found in Perl 5.0, released in 1994. Perl sometimes does incorporate features initially found in other languages. For example, Perl 5.10 implements syntactic extensions originally developed in PCRE and Python.
Lazy matching
In Python and some<!---should be 'many', or 'most', or 'a few', or ...?---> other implementations (e.g. Java), the three common quantifiers (<code>*</code>, <code>+</code>, and <code>?</code>) are greedy by default because they match as many characters as possible. The regex <code>".+"</code> (including the double-quotes) applied to the string
"Ganymede," he continued, "is the largest moon in the Solar System."
matches the entire line (because the entire line begins and ends with a double-quote) instead of matching only the first part, <code>"Ganymede,"</code>. The aforementioned quantifiers may, however, be made lazy or minimal or reluctant, matching as few characters as possible, by appending a question mark: <code>".+?"</code> matches only <code>"Ganymede,"</code>. quantifiers may be made possessive by appending a plus sign, which disables backing off (in a backtracking engine), even if doing so would allow the overall match to succeed: While the regex <code>".*"</code> applied to the string
"Ganymede," he continued, "is the largest moon in the Solar System."
matches the entire line, the regex <code>".*+"</code> does , because <code>.*+</code> consumes the entire input, including the final <code>"</code>. Thus, possessive quantifiers are most useful with negated character classes, e.g. <code>"[^"]*+"</code>, which matches <code>"Ganymede,"</code> when applied to the same string.
Another common extension serving the same function is atomic grouping, which disables backtracking for a parenthesized group. The typical syntax is . For example, while matches both and , only matches because the engine is forbidden from backtracking and so cannot try setting the group to "w" after matching "wi".
Possessive quantifiers are easier to implement than greedy and lazy quantifiers, and are typically more efficient at runtime.
Patterns for non-regular languages
Many features found in virtually all modern regular expression libraries provide an expressive power that exceeds the regular languages. For example, many implementations allow grouping subexpressions with parentheses and recalling the value they match in the same expression ('). This means that, among other things, a pattern can match strings of repeated words like "papa" or "WikiWiki", called squares in formal language theory. The pattern for these strings is <code>(.+)\1</code>.
The language of squares is not regular, nor is it context-free, due to the pumping lemma. However, pattern matching with an unbounded number of backreferences, as supported by numerous modern tools, is still context sensitive. The general problem of matching any number of backreferences is NP-complete, and the execution time for known algorithms grows exponentially by the number of backreference groups used.
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, regexp, or simply pattern to describe the latter. Larry Wall, author of the Perl programming language, writes in an essay about the design of Raku:
