Regular expression


A regular expression is a sequence of characters that define a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. It is a technique developed in theoretical computer science and formal language theory.
The concept arose in the 1950s when the American mathematician Stephen Cole Kleene formalized the description of a regular language. The concept 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, search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK and in lexical analysis. Many programming languages provide regex capabilities either built-in or via libraries.

Patterns

The phrase regular expressions, also called 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 is either a metacharacter, having a special meaning, or a regular character that has a literal meaning. For example, in the regex a., a is a literal character which matches just 'a', while '.' is a metacharacter that matches every character except a newline. Therefore, this regex matches, for example, 'a ', or 'ax', or 'a0'. 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, . is a very general pattern, is less general and a is a precise pattern. 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, the regular expression serialie matches both "serialise" and "serialize". Wildcards 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 ^+|+$ matches excess whitespace at the beginning or end of a line. An advanced regular expression that matches any numeral is ??.


A regex processor translates a regular expression in the above syntax into an internal representation which 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, which is then made deterministic and the resulting deterministic finite automaton is run on the target text string to recognize substrings that match the regular expression.
The picture shows the NFA scheme N obtained from the regular expression s*, where s denotes a simpler regular expression in turn, which has already been recursively translated to the NFA N.

History

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 and the description and classification of formal languages. 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 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. Around the same time when 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 vi, lex, sed, AWK, and expr, and in other programs such as Emacs. 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, who later wrote an implementation of Advanced Regular Expressions for Tcl. 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 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 consolidated. The kernel of the structure specification language standards consists of regexes. Its use is evident in the DTD element group syntax.
Starting in 1997, Philip Hazel developed PCRE, 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, 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. Implementations of regex functionality is often called a regex engine, and a number of libraries are available for reuse. 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.

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 Hndel; we say that this pattern matches each of the three strings. In most formalisms, if there exists at least one regular expression that matches a particular set then there exists an infinite number of other regular expressions that also match it—the specification is not unique. Most formalisms provide the following operations to construct regular expressions.
;Boolean "or"
;Grouping
;Quantification
;Wildcard
The wildcard . matches any character. For example, a.b matches any string that contains an "a", then any other character and then a "b", a.*b matches any string that contains an "a" and a "b" at some later point.
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, Hndel and are both valid patterns which match the same strings as the earlier example, Hndel.
The precise syntax for regular expressions varies among tools and with context; more detail is given in.

Formal language theory

Regular expressions describe regular languages in formal language theory. They have the same expressive power as regular grammars.

Formal definition

Regular expressions consist of constants, which denote sets of strings, and operator symbols, which denote operations over these sets. The following definition is standard, and found as such in most textbooks on formal language theory. Given a finite alphabet Σ, the following constants are defined
as regular expressions:
Given regular expressions R and S, the following operations over them are defined
to produce regular expressions:
To avoid parentheses it is assumed that the Kleene star has the highest priority, then concatenation and then alternation. If there is no ambiguity then parentheses may be omitted. For example, c can be written as abc, and a| can be written as a|bc*.
Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.
Examples:
The formal definition of regular expressions is minimal on purpose, and avoids defining ? and +—these can be expressed as follows: a+ = aa*, and a? = . Sometimes the complement operator is added, to give a generalized regular expression; here Rc matches all strings over Σ* that do not match R. In principle, the complement operator is redundant, because it doesn't grant any more expressive power. However, it can make a regular expression much more concise—eliminating all complement operators from a regular expression 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
Lk consisting of all strings over the alphabet whose kth-from-last letter equals a. On one hand, a regular expression describing L4 is given by
Generalizing this pattern to Lk gives the expression:
On the other hand, it is known that every deterministic finite automaton accepting the language Lk must have at least 2k states. Luckily, there is a simple mapping from regular expressions to the more general nondeterministic finite automata 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.
In the opposite direction, there are many languages easily described by a DFA that are not easily described a regular expression. For instance, determining the validity of a given ISBN requires computing the modulus of the integer base 11, and can be easily implemented with an 11-state DFA. However, a regular expression to answer the same problem of divisibility by 11 is at least multiple megabytes in length.
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, it is worth noting that 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.
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 * and * denote the same regular language, for all regular expressions X, Y, it is necessary and sufficient to check whether the particular regular expressions * and * denote the same language over the alphabet Σ=. 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.
The redundancy can be eliminated by using Kleene star and set union to find an interesting subset of regular expressions that is still fully expressive, but perhaps their use can be restricted. 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

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 as metacharacters. Metacharacters help form: atoms; quantifiers telling how many atoms ; 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 \. Modern and POSIX extended regexes use metacharacters more often than their literal meaning, so to avoid "backslash-osis" or leaning toothpick syndrome it makes sense to have a metacharacter escape to a literal mode; but starting out, it makes more sense to have the four bracketing metacharacters and be primarily literal, and "escape" this usual meaning to become metacharacters. Common standards implement both. The usual metacharacters are ^$.|*+? and \. The usual characters that become metacharacters when escaped are dswDSW and N.

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 re is entered as "re". However, they are often written with slashes as delimiters, as in /re/ for the regex re. This originates in ed, where / is the editor command for searching, and an expression /re/ can be used to specify a range of lines, which can be combined with other commands on either side, most famously g/re/p as in grep, 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 s/re/replacement/ and patterns can be joined with a comma to specify a range of lines as in /re1/,/re2/. 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 s,/,X, will replace a / with an X, using commas as delimiters.

Standards

The IEEE POSIX standard has three sets of compliance: BRE, ERE, and SRE. 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 ?, +, and |, and it removes the need to escape the metacharacters and , 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 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 grep has the following options: "grep -E" for ERE, and "grep -G" for BRE, and "grep -P" 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, and 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 requires that the metacharacters and be designated \ and \, whereas Extended Regular Syntax does not.
MetacharacterDescription
^Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
.Matches any single character. Within POSIX bracket expressions, the dot character matches a literal dot. For example, a.c matches "abc", etc., but matches only "a", ".", or "c".
A bracket expression. Matches a single character that is contained within the brackets. For example, matches "a", "b", or "c". specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: matches "a", "b", "c", "x", "y", or "z", as does .
The - character is treated as a literal character if it is the last or the first character within the brackets: , . Note that backslash escapes are not allowed. The ] character can be included in a bracket expression if it is the first character: abc].
Matches a single character that is not contained within the brackets. For example, matches any character other than "a", "b", or "c". matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed.
$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. A marked subexpression is also called a block or capturing group. BRE mode requires .
\nMatches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is vaguely defined in the POSIX.2 standard. Some tools allow referencing more than nine capturing groups. Also known as a backreference.
*Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc. * matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. * 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 regexes. BRE mode requires .

Examples:
The meaning of metacharacters escaped with a backslash is reversed for some characters in the POSIX Extended Regular Expression 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:
MetacharacterDescription
?Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc".
+Matches the preceding element one or more times. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
|The choice operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

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

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, could stand for the uppercase alphabet in the English language, and \d could mean any digit. Character classes apply to both POSIX levels.
When specifying a range of characters, such as , 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:
POSIXNon-standardPerl/TclVimJavaASCIIDescription
\pASCII characters
\pAlphanumeric characters
\w\w\wAlphanumeric characters plus "_"
\W\W\WNon-word characters
\a\pAlphabetic characters
\s\pSpace and tab
\b\< \>\b|Word boundaries
\B|Non-word boundaries
\pControl characters
\d\d\p or \dDigits
\D\D\DNon-digits
\pVisible characters
\l\pLowercase letters
\p\pVisible characters and the space character
\pab] matches the uppercase letters and lowercase "a" and "b".
An additional non-POSIX class understood by some tools is , which is usually defined as 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 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 \h\w* or :alpha:]_]:alnum:]_]* 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 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 other implementations, the three common quantifiers are greedy by default because they match as many characters as possible. The regex ".+" applied to the string
"Ganymede," he continued, "is the largest moon in the Solar System."
matches the entire line instead of matching only the first part, "Ganymede,". The aforementioned quantifiers may, however, be made lazy or minimal or reluctant, matching as few characters as possible, by appending a question mark: ".+?" matches only "Ganymede,".
However, the whole sentence can still be matched in some circumstances. The question-mark operator does not change the meaning of the dot operator, so this still can match the double-quotes in the input. A pattern like ".*?" EOF will still match the whole input if this is the string:
"Ganymede," he continued, "is the largest moon in the Solar System." EOF
To ensure that the double-quotes cannot be part of the match, the dot has to be replaced. This will match a quoted text part without additional double-quotes in it.

Possessive matching

In Java, quantifiers may be made possessive by appending a plus sign, which disables backing off, even if doing so would allow the overall match to succeed: While the regex ".*" applied to the string
"Ganymede," he continued, "is the largest moon in the Solar System."
matches the entire line, the regex ".*+" does, because .*+ consumes the entire input, including the final ". Thus, possessive quantifiers are most useful with negated character classes, e.g. "*+", which matches "Ganymede," 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 try with setting the group as "w".
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 \1.
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, growing exponentially by the number of backref 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:
Other features not found in describing regular languages include assertions. These include the ubiquitous and, as well as some more sophiscated extensions like lookaround. They define the surrounding of a match and don't spill into the match itself, a feature only relevant for the use-case of string searching. Some of them can be simulated in a regular language by treating the surroundings as a part of the language as well.

Implementations and running times

There are at least three different algorithms that decide whether and how a given regex matches a string.
The oldest and fastest relies on a result in formal language theory that allows every nondeterministic finite automaton to be transformed into a deterministic finite automaton. 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, but it can be run on a string of size n in time O. Note that the size of the expression is the size after abbreviations, such as numeric quantifiers, have been expanded.
An alternative approach is to simulate the NFA directly, essentially building each DFA state on demand and then discarding it at the next step. This keeps the DFA implicit and avoids the exponential construction cost, but running cost rises to O. The explicit approach is called the DFA algorithm and the implicit approach the NFA algorithm. Adding caching to the NFA algorithm is often called the "lazy DFA" algorithm, or just the DFA algorithm without making a distinction. These algorithms are fast, but using them for recalling grouped subexpressions, lazy quantification, and similar features is tricky. Modern implementations include the re1-re2-sregex family based on Cox's code.
The third algorithm is to match the pattern against the input string by backtracking. This algorithm is commonly called NFA, but this terminology can be confusing. Its running time can be exponential, which simple implementations exhibit when matching against expressions like that contain both alternation and unbounded quantification and force the algorithm to consider an exponentially increasing number of sub-cases. This behavior can cause a security problem called Regular expression Denial of Service.
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 include some kind of backtracking. Some implementations try to provide the best of both algorithms by first running a fast DFA algorithm, and revert to a potentially slower backtracking algorithm only when a backreference is encountered during the match. GNU grep uses such a strategy.
Sublinear runtime algorithms have been achieved using Boyer-Moore based algorithms and related DFA optimization techniques such as the reverse scan. GNU grep, which supports a wide variety of POSIX syntaxes and extensions, uses BM for a first-pass prefiltering, and then uses an implicit DFA. Wu agrep, which implements approximate matching, combines the prefiltering into the DFA in BDM. NR-grep's BNDM extends the BDM technique with Shift-Or bit-level parallelism.
A few theoretical alternatives to backtracking for backreferences exist, and their "exponents" are tamer in that they are only related to the number of backreferences, a fixed property of some regexp languages such as POSIX. One naive method that duplicates a non-backtracking NFA for each backreference note has a complexity of time and space for a haystack of length n and k backreferences in the RegExp. A very recent theoretical work based on memory automata gives a tighter bound based on "active" variable nodes used, and a polynomial possibility for some backreferenced regexps.

Unicode

In theoretical terms, any token set can be matched by regular expressions as long as it is pre-defined. In terms of historical implementations, regexes were originally written to use ASCII characters as their token set though regex libraries have supported numerous other character sets. Many modern regex engines offer at least some support for Unicode. In most respects it makes no difference what the character set is, but some issues do arise when extending regexes to support Unicode.
  • Supported encoding. Some regex libraries expect to work on some particular encoding instead of on abstract Unicode characters. Many of these require the UTF-8 encoding, while others might expect UTF-16, or UTF-32. In contrast, Perl and Java are agnostic on encodings, instead operating on decoded characters internally.
  • Supported Unicode range. Many regex engines support only the Basic Multilingual Plane, that is, the characters which can be encoded with only 16 bits. Currently only a few regex 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 are valid wherever x and y have code points in the range and codepoint ≤ codepoint. The natural extension of such character ranges to Unicode would simply change the requirement that the endpoints lie in to the requirement that they lie in . 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 is valid since both endpoints fall within the Basic Latin block, as is since both endpoints fall within the Armenian block, but a range like is invalid since it includes multiple Unicode blocks. Other engines, such as that of the Vim editor, allow block-crossing but the character values must not be more than 256 apart.
  • 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 ASCII has case distinction, case insensitivity became a logical feature in text searching. Unicode introduced alphabetic scripts without case like Devanagari. 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. In Japanese, insensitivity between hiragana and katakana is sometimes useful.
  • Normalization. Unicode has combining characters. Like old typewriters, plain letters can be followed by one or more non-spacing symbols to form a single printing character, but also provides precomposed characters, i.e. characters that already include one or more combining characters. A sequence of a character + combining character should be matched with the identical single precomposed character. The process of standardizing sequences of characters + combining characters is called normalization.
  • 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, scripts, and numerous other character properties. Block properties are much less useful than script properties, because a block can have code points from several different scripts, and a script can have code points from several different blocks. In Perl and the library, properties of the form \p or \p match characters in block X and \P or \P matches code points not in that block. Similarly, \p, \p, or \p matches any character in the Armenian script. In general, \p matches any character with either the binary property X or the general category X. For example, \p, \p, or \p matches any uppercase letter. Binary properties that are not general categories include \p, \p, \p, and \p. Examples of non-binary properties are \p, \p, and \p.

    Uses

Regexes are useful in a wide variety of text processing tasks, and more generally string processing, where the data need not be textual. Common applications include data validation, data scraping, data wrangling, simple parsing, the production of syntax highlighting systems, and many other tasks.
While regexes would be useful on Internet search engines, 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. Notable exceptions: Google Code Search, Exalead. Google Code Search has been shut down as of January 2012.
It used a trigram index to speed queries.

Examples

The specific syntax rules vary depending on the specific implementation, programming language, or library in use. Additionally, the functionality of regex implementations can vary between versions.
Because regexes can be difficult to both explain and understand without examples, interactive websites for testing regexes are a useful resource for learning regexes by experimentation.
This section provides a basic description of some of the properties of regexes by way of illustration.
The following conventions are used in the examples.
metacharacter ;; the metacharacters column specifies the regex syntax being demonstrated
=~ m// ;; indicates a regex match operation in Perl
=~ s/// ;; indicates a regex substitution operation in Perl
Also worth noting is that these regexes are all Perl-like syntax. Standard POSIX regular expressions are different.
Unless otherwise indicated, the following examples conform to the Perl programming language, release 5.8.8, January 31, 2006. This means that other implementations may lack support for some parts of the syntax shown here vs. , or lack of \d instead of POSIX ).
The syntax and conventions used in these examples coincide with that of other programming environments as well.
Meta­characterDescriptionExample
.Normally matches any character except a newline.
Within square brackets the dot is literal.

$string1 = "Hello World\n";
if

Output:

Hello World
has length >= 5.
Groups a series of pattern elements to a single element.
When you match a pattern within parentheses, you can use any of $1, $2,... later to refer to the previously matched pattern.

$string1 = "Hello World\n";
if.

Output:

We matched 'Hel' and 'o W'.
+Matches the preceding pattern element one or more times.
$string1 = "Hello World\n";
if

Output:

There are one or more consecutive letter "l"'s in Hello World.
?Matches the preceding pattern element zero or one time.
$string1 = "Hello World\n";
if

Output:

There is an 'H' and a 'e' separated by 0-1 characters.
?Modifies the *, +, ? or 'd regex that comes before to match as few times as possible.
$string1 = "Hello World\n";
if

Output:

The non-greedy match with 'l' followed by one or more characters is 'llo' rather than 'llo Wo'.
*Matches the preceding pattern element zero or more times.
$string1 = "Hello World\n";
if

Output:

There is an 'e' followed by zero to many 'l' followed by 'o'.
Denotes the minimum M and the maximum N match count.
N can be omitted and M can be 0: matches "exactly" M times; matches "at least" M times; matches "at most" N times.
x* y+ z? is thus equivalent to x y z.

$string1 = "Hello World\n";
if

Output:

There exists a substring with at least 1 and at most 2 l's in Hello World
Denotes a set of possible character matches.
$string1 = "Hello World\n";
if

Output:

Hello World
contains one or more vowels.
|Separates alternate possibilities.
$string1 = "Hello World\n";
if

Output:

Hello World
contains at least one of Hello, Hi, or Pogo.
\bMatches a zero-width boundary between a word-class character and either a non-word class character or an edge; same as
.

$string1 = "Hello World\n";
if

Output:

There is a word that ends with 'llo'.
\wMatches an alphanumeric character, including "_";
same as in ASCII, and
in Unicode, where the Alphabetic property contains more than Latin letters, and the Decimal_Number property contains more than Arab digits.

$string1 = "Hello World\n";
if

Output:

There is at least one alphanumeric character in Hello World
.
\WMatches a non-alphanumeric character, excluding "_";
same as in ASCII, and
in Unicode.

$string1 = "Hello World\n";
if

Output:

The space between Hello and World is not alphanumeric.
\sMatches a whitespace character,
which in ASCII are tab, line feed, form feed, carriage return, and space;
in Unicode, also matches no-break spaces, next line, and the variable-width spaces.

$string1 = "Hello World\n";
if

Output:

In Hello World
there are TWO whitespace characters, which may be separated by other characters.
\SMatches anything but a whitespace.
$string1 = "Hello World\n";
if

Output:

In Hello World
there are TWO non-whitespace characters, which may be separated by other characters.
\dMatches a digit;
same as in ASCII;
in Unicode, same as the \p or \p property, which itself the same as the \p property.

$string1 = "99 bottles of beer on the wall.";
if

Output:

99 is the first number in '99 bottles of beer on the wall.'
\DMatches a non-digit;
same as in ASCII or \P in Unicode.

$string1 = "Hello World\n";
if

Output:

There is at least one character in Hello World
that is not a digit.
^Matches the beginning of a line or string.
$string1 = "Hello World\n";
if

Output:

Hello World
starts with the characters 'He'.
$Matches the end of a line or string.
$string1 = "Hello World\n";
if

Output:

Hello World
is a line or string that ends with 'rld'.
\AMatches the beginning of a string.
$string1 = "Hello\nWorld\n";
if

Output:

Hello
World
is a string that starts with 'H'.
\zMatches the end of a string.
$string1 = "Hello\nWorld\n";
if

Output:

Hello
World
is a string that ends with 'd\n'.
Matches every character except the ones inside brackets.
$string1 = "Hello World\n";
if

Output:

Hello World
contains a character other than a, b, and c.

Induction

Regular expressions can often be created based on a set of example strings. This is known as the induction of regular languages, and is part of the general problem of grammar induction in computational learning theory. Formally, given examples of strings in a regular language, and perhaps also given examples of strings not in that regular language, it is possible to induce a grammar for the language, i.e., a regular expression that generates that language. Not all regular languages can be induced in this way, but many can. For example, the set of examples, and negative set can be used to induce the regular expression 1⋅0*.
OWIKI.org. Text is available under the Creative Commons Attribution-ShareAlike License.