History
g/''re''/p
meaning "Global search for Regular Expression and Print matching lines"). 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 LIKE
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 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 regexb.
, '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, .
is a very general pattern, -z/nowiki>
(match all lower case letters from 'a' to 'z') is less general and b
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 seriali z
matches both "serialise" and "serialize". ''N''(''s''*)
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''(''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 patternH(ä, ae?)ndel
; 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, (Hän, Han, Haen)del
also specifies the same set of three strings in this example.
Most formalisms provide the following operations to construct regular expressions.
; Boolean "or" :
: A gray, grey
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 ?
, the *
(derived from the +
( Kleene plus).
:
; Wildcard :
: The wildcard .
matches any character. For example,
:: a.b
matches any string that contains an "a", and then any character and then "b".
:: a.*b
matches any string that contains an "a", and then the character "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 ÷.
The precise Formal language theory
Regular expressions describeFormal 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 finitea
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:
* (''(RS)
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 and S denote . Then, (RS)
denotes .
* ('' alternation'') (R, S)
denotes the (R, S)
describes .
* (''(R*)
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 , (R*)
denotes the set of all finite binary strings (including the empty string). If R denotes , (R*)
denotes .
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, (ab)c
can be written as abc
, and a, (b(c*))
can be written as a, bc*
. Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.
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, ε)
denotes the set of strings starting with "a", then zero or more "b"s and finally optionally a "c":
* (0, (1(01*0)*1))*
denotes the set of binary numbers that are multiples of 3:
Expressive power and compactness
The formal definition of regular expressions is minimal on purpose, and avoids defining?
and +
—these can be expressed as follows: a+
=aa*
, and a?
=(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 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
''Lk'' consisting of all strings over the alphabet whose ''k''th-from-last letter equals ''a''. On the one hand, a regular expression describing ''L''4 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 2''k'' 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.
In the opposite direction, there are many languages easily described by a DFA that are not easily described by a regular expression. For instance, determining the validity of a given 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 anSyntax
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 (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 \
. 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 ( )
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 regexre
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 (matching the pattern), which can be combined with other commands on either side, most famously g/re/p
as in grep ("global regex print"), which is included in most Unix-based operating systems, such as 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 s,/,X,
will replace a /
with an X
, using commas as delimiters.
IEEE POSIX Standard
The?
, +
, 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 (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 grep
has the following options: "grep -E
" for ERE, and "grep -G
" for BRE (the default), and "grep -P
" for ( )
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( )
and
be designated \(\)
and \
, whereas Extended Regular Syntax (ERE) does not.
Examples:
* .at
matches any three-character string ending with "at", including "hat", "cat", "bat", "4at", "#at" and " at" (starting with a space).
* ct
matches "hat" and "cat".
* bt
matches all strings matched by .at
except "bat".
* hct
matches all strings matched by .at
other than "hat" and "cat".
* ^ ct
matches "hat" and "cat", but only at the beginning of the string or line.
* ct$
matches "hat" and "cat", but only at the end of the string or line.
* \ \/code> matches any single character surrounded by " and " since the brackets are escaped, for example: " , " , " , " , "[", and "[ ]" (bracket space bracket).
* s.*
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, \( \)
is now ( )
and \
is now
. Additionally, support is removed for \''n''
backreferences and the following metacharacters are added:
Examples:
* cat
matches "at", "hat", and "cat".
* cat
matches "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on.
* cat
matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "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.
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, -Z/syntaxhighlight> could stand for any uppercase letter in the English alphabet, and \d could mean any digit. Character classes apply to both POSIX levels.
When specifying a range of characters, such as -Z/syntaxhighlight> (i.e. lowercase ''a '' to uppercase ''Z ''), 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:
POSIX character classes can only be used within bracket expressions. For example, :upper:b] matches the uppercase letters and lowercase "a" and "b".
An additional non-POSIX class understood by some tools is word:/syntaxhighlight>, which is usually defined as 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 \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: 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 (relative) ease of reading, many other utilities and programming languages have adopted syntax similar to Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
's—for example, Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
, JavaScript
JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior.
Web browsers have ...
, Julia, Python, Ruby, Qt, Microsoft's .NET Framework, and XML Schema
An XML schema is a description of a type of XML document, typically expressed in terms of constraints on the structure and content of documents of that type, above and beyond the basic syntactical constraints imposed by XML itself. These constrai ...
. 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 (e.g. Java), the three common quantifiers (*
, +
and ?
) are greedy by default because they match as many characters as possible. The regex ".+"
(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, "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,"
.
Possessive matching
In Java and Python 3.11+, 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 ".*"
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 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.
IETF I-Regexp
IETF RFC 9485 describes "I-Regexp: An Interoperable Regular Expression Format". It specifies a limited subset of regular-expression idioms designed to be interoperable, i.e. produce the same effect, in a large number of regular-expression libraries. I-Regexp is also limited to matching, i.e. providing a true or false match between a regular expression and a given piece of text. Thus, it lacks advanced features such as capture groups, lookahead, and backreferences.
Patterns for non-regular languages
Many features found in virtually all modern regular expression libraries provide an expressive power that exceeds the regular language
In theoretical computer science and formal language theory, a regular language (also called a rational language) is a formal language that can be defined by a regular expression, in the strict sense in theoretical computer science (as opposed to ...
s. 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, 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
In logic, mathematics, computer science, and linguistics, a formal language is a set of string (computer science), strings whose symbols are taken from a set called "#Definition, alphabet".
The alphabet of a formal language consists of symbol ...
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:
Assertions
Other features not found in describing regular languages include assertions. These include the ubiquitous and , used since at least 1970, as well as some more sophisticated extensions like lookaround that appeared in 1994. Lookarounds define the surrounding of a match and do not 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.
The and have been attested since at least 1994, starting with Perl 5. The lookbehind assertions and are attested since 1997 in a commit by Ilya Zakharevich to Perl 5.005.
Implementations and running times
There are at least three different algorithm
In mathematics and computer science, an algorithm () is a finite sequence of Rigour#Mathematics, mathematically rigorous instructions, typically used to solve a class of specific Computational problem, problems or to perform a computation. Algo ...
s 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
In automata theory, a finite-state machine is called a deterministic finite automaton (DFA), if
* each of its transitions is ''uniquely'' determined by its source state and input symbol, and
* reading an input symbol is required for each state tr ...
(NFA) to be transformed into a deterministic finite automaton (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''(2''m''), but it can be run on a string of size ''n'' in time ''O''(''n''). 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''(''mn''). 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
A regular expression denial of service (ReDoS)
is an algorithmic complexity attack that produces a denial-of-service by providing a regular expression and/or an input that takes a long time to evaluate. The attack exploits the fact that many Regu ...
(ReDoS).
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 (and the underlying gnulib DFA) uses such a strategy.
Sublinear runtime algorithms have been achieved using Boyer-Moore (BM) 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 (backward DAWG matching). 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
ASCII ( ), an acronym for American Standard Code for Information Interchange, is a character encoding standard for representing a particular set of 95 (English language focused) printable character, printable and 33 control character, control c ...
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
Unicode or ''The Unicode Standard'' or TUS is a character encoding standard maintained by the Unicode Consortium designed to support the use of text in all of the world's writing systems that can be digitized. Version 16.0 defines 154,998 Char ...
. 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
UTF-8 is a character encoding standard used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode Transformation Format 8-bit''. Almost every webpage is transmitted as UTF-8.
UTF-8 supports all 1,112,0 ...
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 (as of ) only a few regex engines (e.g., Perl's and Java's) 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 -y/code> are valid wherever ''x'' and ''y'' have code point
A code point, codepoint or code position is a particular position in a Table (database), table, where the position has been assigned a meaning. The table may be one dimensional (a column), two dimensional (like cells in a spreadsheet), three dime ...
s in the range x00,0x7Fand codepoint(''x'') ≤ codepoint(''y''). The natural extension of such character ranges to Unicode would simply change the requirement that the endpoints lie in x00,0x7Fto the requirement that they lie in x0000,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 x61,0x7Fis valid since both endpoints fall within the Basic Latin block, as is x0530,0x0560since both endpoints fall within the Armenian block, but a range like x0061,0x0532is 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
Devanagari ( ; in script: , , ) is an Indic script used in the Indian subcontinent. It is a left-to-right abugida (a type of segmental Writing systems#Segmental systems: alphabets, writing system), based on the ancient ''Brāhmī script, Brā ...
. 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
is a Japanese language, Japanese syllabary, part of the Japanese writing system, along with ''katakana'' as well as ''kanji''.
It is a phonetic lettering system. The word ''hiragana'' means "common" or "plain" kana (originally also "easy", ...
and katakana
is a Japanese syllabary, one component of the Japanese writing system along with hiragana, kanji and in some cases the Latin script (known as rōmaji).
The word ''katakana'' means "fragmentary kana", as the katakana characters are derived fr ...
is sometimes useful.
* Normalization. Unicode has combining characters. Like old typewriters, plain base characters (white spaces, punctuation characters, symbols, digits, or letters) can be followed by one or more non-spacing symbols (usually diacritics, like accent marks modifying letters) to form a single printable character; but Unicode also provides a limited set of precomposed characters, i.e. characters that already include one or more combining characters. A sequence of a base character + combining characters should be matched with the identical single precomposed character (only some of these combining sequences can be precomposed into a single Unicode character, but infinitely many other combining sequences are possible in Unicode, and needed for various languages, using one or more combining characters after an initial base character; these combining sequences ''may'' include a base character or combining characters partially precomposed, but not necessarily in canonical order and not necessarily using the canonical precompositions). The process of standardizing sequences of a base character + combining characters by decomposing these ''canonically equivalent'' sequences, before reordering them into canonical order (and optionally recomposing ''some'' combining characters into the leading base character) is called normalization.
* New control codes. Unicode introduced, among other codes, 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
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
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
.
Language support
Most general-purpose programming language
In computer software, a general-purpose programming language (GPL) is a programming language for building software in a wide variety of application Domain (software engineering), domains. Conversely, a Domain-specific language, domain-specific pro ...
s support regex capabilities, either natively or via libraries.
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
In computing, data validation or input validation is the process of ensuring data has undergone data cleansing to confirm it has data quality, that is, that it is both correct and useful. It uses routines, often called "validation rules", "valida ...
, data scraping
Data scraping is a technique where a computer program extracts data from Human-readable medium, human-readable output coming from another program.
Description
Normally, Data transmission, data transfer between programs is accomplished using data ...
(especially web scraping
Web scraping, web harvesting, or web data extraction is data scraping used for data extraction, extracting data from websites. Web scraping software may directly access the World Wide Web using the Hypertext Transfer Protocol or a web browser. W ...
), data wrangling, simple parsing
Parsing, syntax analysis, or syntactic analysis is a process of analyzing a String (computer science), string of Symbol (formal), symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal gramm ...
, the production of syntax highlighting systems, and many other tasks.
Some high-end desktop publishing
Desktop publishing (DTP) is the creation of documents using dedicated software on a personal ("desktop") computer. It was first used almost exclusively for print publications, but now it also assists in the creation of various forms of online co ...
software has the ability to use regexes to automatically apply text styling, saving the person doing the layout from laboriously doing this by hand for anything that can be matched by a regex. For example, by defining a character style that makes text into small caps
In typography, small caps (short for small capitals) are grapheme, characters typeset with glyphs that resemble uppercase letters but reduced in height and weight close to the surrounding lowercase letters or text figures. Small caps are used i ...
and then using the regex -Z/code> to apply that style, any word of four or more consecutive capital letters will be automatically rendered as small caps instead.
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 include Google Code Search and Exalead. However, Google Code Search was shut down in January 2012.
Examples
The specific syntax rules vary depending on the specific implementation, programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
, or library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
in use. Additionally, the functionality of regex implementations can vary between versions
Version may refer to:
Computing
* Software version, a set of numbers that identify a unique evolution of a computer program
* VERSION (CONFIG.SYS directive), a configuration directive in FreeDOS
Music
* Cover version
* Dub version
* Remix
* Versi ...
.
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.The character 'm' is not always required to specify a Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
match operation. For example, m/ abc
could also be rendered as / abc
. The 'm' is only necessary if the user wishes to specify a match operation without using a forward-slash as the regex delimiter. Sometimes it is useful to specify an alternate regex delimiter in order to avoid " delimiter collision". See
perldoc perlre
' for more details.
metacharacter(s) ;; 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
These regexes are all Perl-like syntax. Standard POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
regular expressions are different.
Unless otherwise indicated, the following examples conform to the Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
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 (e.g. basic vs. extended regex, \( \)
vs. ()
, or lack of \d
instead of POSIX
The Portable Operating System Interface (POSIX; ) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines application programming interfaces (APIs), along with comm ...
digit:/code>).
The syntax and conventions used in these examples coincide with that of other programming environments as well.E.g., see ''Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
in a Nutshell'', p. 213; '' Python Scripting for Computational Science'', p. 320; Programming PHP, p. 106.
Induction
Regular expressions can often be created ("induced" or "learned") 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
In computer science, computational learning theory (or just learning theory) is a subfield of artificial intelligence devoted to studying the design and analysis of machine learning algorithms.
Overview
Theoretical results in machine learning m ...
. 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 (see language identification in the limit), but many can. For example, the set of examples , and negative set (of counterexamples) can be used to induce the regular expression 1⋅0* (1 followed by zero or more 0s).
See also
* Comparison of regular expression engines
* Extended Backus–Naur form
* Matching wildcards
* Regular tree grammar
* Thompson's construction – converts a regular expression into an equivalent nondeterministic finite automaton (NFA)
Notes
References
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
External links
*
* ISO/IEC/IEEE 9945:200
''Information technology – Portable Operating System Interface (POSIX) Base Specifications, Issue 7''
Open source list of regular expression resources
{{Authority control
1951 introductions
Articles with example code
Automata (computation)
Formal languages
Pattern matching
Programming constructs