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, 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 ab.
, '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 itsH(ä, 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 vertical bar separates alternatives. For example, can match "gray" or "grey".
;Grouping
:gray, grey
and are equivalent patterns which both describe the set of "gray" or "grey".
;Quantification
:A quantifier after an element (such as a ?
, 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"; and 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 syntax for regular expressions varies among tools and with context; more detail is given in .
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 (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, then concatenation and 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 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 \
. Modern and POSIX extended regexes use metacharacters more often than their literal meaning, so to avoid "backslash-osis" or ( )
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 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.
Standards
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".
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
A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
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
Vim means enthusiasm and vigor. It may also refer to:
* Vim (cleaning product)
* Vim Comedy Company, a movie studio
* Vim Records
* Vimentin, a protein
* "Vim", a song by Machine Head on the album ''Through the Ashes of Empires''
* Vim (text ed ...
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 family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
's — for example, Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
, JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, Julia (programming language), Julia, Python, Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
, Qt, Microsoft's .NET Framework
The .NET Framework (pronounced as "''dot net"'') is a proprietary software framework developed by Microsoft that runs primarily on Microsoft Windows. It was the predominant implementation of the Common Language Infrastructure (CLI) until bein ...
, and XML Schema
An XML schema is a description of a type of Extensible Markup Language, 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 ...
. Some languages and tools such as Boost
Boost, boosted or boosting may refer to:
Science, technology and mathematics
* Boost, positive manifold pressure in turbocharged engines
* Boost (C++ libraries), a set of free peer-reviewed portable C++ libraries
* Boost (material), a material b ...
and PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
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.
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
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
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
In computational complexity theory, a problem is NP-complete when:
# it is a problem for which the correctness of each solution can be verified quickly (namely, in polynomial time) and a brute-force search algorithm can find a solution by tryin ...
, 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
In logic, mathematics, computer science, and linguistics, a formal language consists of words whose letters are taken from an alphabet and are well-formed according to a specific set of rules.
The alphabet of a formal language consists of sy ...
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
Larry Arnold Wall (born September 27, 1954) is an American computer programmer and author. He created the Perl programming language.
Personal life
Wall grew up in Los Angeles and then Bremerton, Washington, before starting higher education at ...
, 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 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.
The look-ahead assertions (?=…)
and (?!…)
have been attested since at least 1994, starting with Perl 5. The look-behind 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 rigorous instructions, typically used to solve a class of specific problems or to perform a computation. Algorithms are used as specifications for performing ...
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 t ...
(NFA) to be transformed into a deterministic finite automaton
In the theory of computation, a branch of theoretical computer science, a deterministic finite automaton (DFA)—also known as deterministic finite acceptor (DFA), deterministic finite-state machine (DFSM), or deterministic finite-state automa ...
(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
Backtracking is a class of algorithms for finding solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate ("backtracks") as soon as it de ...
. 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 (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
agrep (approximate grep) is an open-source approximate string matching program, developed by Udi Manber and Sun Wu between 1988 and 1991, for use with the Unix operating system. It was later ported to OS/2, DOS, and Windows.
It selects the best-s ...
, 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 ( ), abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Because ...
characters as their token set though regex libraries have supported numerous other character set
Character encoding is the process of assigning numbers to graphical characters, especially the written characters of human language, allowing them to be stored, transmitted, and transformed using digital computers. The numerical values tha ...
s. Many modern regex engines offer at least some support for Unicode
Unicode, formally The Unicode Standard,The formal version reference is is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world's writing systems. The standard, ...
. 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 variable-length character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from ''Unicode'' (or ''Universal Coded Character Set'') ''Transformation Format 8-bit''.
UTF-8 is capable of ...
encoding, while others might expect UTF-16
UTF-16 (16-bit Unicode Transformation Format) is a character encoding capable of encoding all 1,112,064 valid code points of Unicode (in fact this number of code points is dictated by the design of UTF-16). The encoding is variable-length, as cod ...
, 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
In the Unicode standard, a plane is a continuous group of 65,536 (216) code points. There are 17 planes, identified by the numbers 0 to 16, which corresponds with the possible values 00–1016 of the first two positions in six position hexadecim ...
, 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
In character encoding terminology, a code point, codepoint or code position is a numerical value that maps to a specific character. Code points usually represent a single grapheme—usually a letter, digit, punctuation mark, or whitespace—bu ...
s in the range x00,0x7F
X, or x, is the twenty-fourth and third-to-last letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''"ex"'' (pronounced ), ...
and codepoint(''x'') ≤ codepoint(''y''). The natural extension of such character ranges to Unicode would simply change the requirement that the endpoints lie in x00,0x7F
X, or x, is the twenty-fourth and third-to-last letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''"ex"'' (pronounced ), ...
to the requirement that they lie in x0000,0x10FFFF
X, or x, is the twenty-fourth and third-to-last letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''"ex"'' (pronounced ), ...
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,0x0560
X, or x, is the twenty-fourth and third-to-last Letter (alphabet), letter in the Latin alphabet, used in the English alphabet, modern English alphabet, the alphabets of other western European languages and others worldwide. Its English a ...
since both endpoints fall within the Armenian block, but a range like x0061,0x0532
X, or x, is the twenty-fourth and third-to-last letter in the Latin alphabet, used in the modern English alphabet, the alphabets of other western European languages and others worldwide. Its name in English is ''"ex"'' (pronounced ) ...
is invalid since it includes multiple Unicode blocks. Other engines, such as that of the Vim
Vim means enthusiasm and vigor. It may also refer to:
* Vim (cleaning product)
* Vim Comedy Company, a movie studio
* Vim Records
* Vimentin, a protein
* "Vim", a song by Machine Head on the album ''Through the Ashes of Empires''
* Vim (text ed ...
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 ( ; , , Sanskrit pronunciation: ), also called Nagari (),Kathleen Kuiper (2010), The Culture of India, New York: The Rosen Publishing Group, , page 83 is a left-to-right abugida (a type of segmental writing system), based on the a ...
. For these, case sensitivity In computers, case sensitivity defines whether uppercase and lowercase letters are treated as distinct (case-sensitive) or equivalent (case-insensitive). For instance, when users interested in learning about dogs search an e-book, "dog" and "Dog" ...
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'' literally means "flowing" or "simple" kana ("simple" ori ...
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 f ...
is sometimes useful.
* Normalization. Unicode has combining characters
In digital typography, combining characters are characters that are intended to modify other characters. The most common combining characters in the Latin script are the combining diacritical marks (including combining accents).
Unicode al ...
. 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 amongst others, byte order mark
The byte order mark (BOM) is a particular usage of the special Unicode character, , whose appearance as a magic number at the start of a text stream can signal several things to a program reading the text:
* The byte order, or endianness, of ...
s 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 family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
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
String functions are used in computer programming languages to manipulate a string or query information about a string (some do both).
Most programming languages that have a string datatype will have some string functions although there may ...
, where the data need not be textual. Common applications include data validation, data scraping (especially web scraping
Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. Web scraping software may directly access the World Wide Web using the Hypertext Transfer Protocol or a web browser. While web scrapin ...
), data wrangling, simple parsing
Parsing, syntax analysis, or syntactic analysis is the process of analyzing a string of symbols, either in natural language, computer languages or data structures, conforming to the rules of a formal grammar. The term ''parsing'' comes from Lati ...
, the production of syntax highlighting
Syntax highlighting is a feature of text editors that are used for programming, scripting, or markup languages, such as HTML. The feature displays text, especially source code, in different colours and fonts according to the category of terms. ...
systems, and many other tasks.
While regexes would be useful on Internet search engine
A search engine is a software system designed to carry out web searches. They search the World Wide Web in a systematic way for particular information specified in a textual web search query. The search results are generally presented in a ...
s, 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. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
, or library
A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vi ...
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.The character 'm' is not always required to specify a Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
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
A delimiter is a sequence of one or more characters for specifying the boundary between separate, independent regions in plain text, mathematical expressions or other data streams. An example of a delimiter is the comma character, which acts as ...
". 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
Also worth noting is that 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 both the system- and user-level application programming inte ...
regular expressions are different.
Unless otherwise indicated, the following examples conform to the Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
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 both the system- and user-level application programming inte ...
digit:/code>).
The syntax and conventions used in these examples coincide with that of other programming environments as well.E.g., see ''Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
in a Nutshell'', p. 213; '' Python Scripting for Computational Science'', p. 320; Programming PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
, 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 In computational learning theory, induction of regular languages refers to the task of learning a formal description (e.g. grammar) of a regular language from a given set of example strings. Although E. Mark Gold has shown that not every regular l ...
and is part of the general problem of grammar induction
Grammar induction (or grammatical inference) is the process in machine learning of learning a formal grammar (usually as a collection of ''re-write rules'' or '' productions'' or alternatively as a finite state machine or automaton of some kind) fr ...
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 (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
This is a comparison of regular expression engines.
Libraries
Languages
Language features
NOTE: An application using a library for regular expression support does not necessarily offer the full set of features of the library, e.g. GNU gre ...
* Extended Backus–Naur form
In computer science, extended Backus–Naur form (EBNF) is a family of metasyntax notations, any of which can be used to express a context-free grammar. EBNF is used to make a formal description of a formal language such as a computer programmi ...
* 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 9945-2:199
''Information technology – Portable Operating System Interface (POSIX) – Part 2: Shell and Utilities''
* ISO/IEC 9945-2:200
* ISO/IEC 9945-2:2003 ttp://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=38790 ''Information technology – Portable Operating System Interface (POSIX) – Part 2: System Interfaces''* ISO/IEC/IEEE 9945:200
''Information technology – Portable Operating System Interface (POSIX®) Base Specifications, Issue 7''
{{Authority control
Automata (computation)
Formal languages
Pattern matching
Programming constructs
Articles with example code
1951 introductions