Random variable: Difference between revisions

From formulasearchengine
Jump to navigation Jump to search
en>Nijdam
Undid revision 591829617 by 99.241.166.168 (talk) the opposite of improvement
en>Aldaron
Line 1: Line 1:
[[File:The river effect in justified text.jpg|thumb|right|The regular expression <br><code>{{hl|1=(?<=\.)&nbsp;{2,}(?=[A-Z])}}</code> matches at least two spaces occurring after period (.) and before an upper case letter as highlighted in the text above.]]
I would like to introduce myself to you, I am Natalie and [http://www.Bbc.co.uk/search/?q=I+adore I adore] it. Delaware is where we've been residing for many years but my husband wants us to transfer. She is an workplace supervisor but she plans on altering it. Bottle tops collecting is the only hobby my wife doesn't approve of. See what's new on my web site right here: http://punterpedia.com/wiki/How_To_Find_Out_Everything_There_Is_To_Know_About_Nya_Internet_Svenska_Casinon_P%C3%A5_N%C3%A4tet_In_4_Simple_Steps<br><br>
In [[theoretical computer science]] and [[formal language theory]], a '''regular expression''' (abbreviated '''regex''' or '''regexp''') is a sequence of [[Character (computing)|characters]] that forms a search pattern, mainly for use in [[pattern matching]] with [[String (computer science)|strings]], or [[string matching]], i.e. "find and replace"-like operations.  The concept arose in the 1950s, when the American mathematician [[Stephen Cole Kleene|Stephen Kleene]] formalized the description of a ''[[regular language]]'', and came into common use with the [[Unix]] text processing utilities [[ed (text editor)|ed]], an editor, and [[grep]] (global regular expression print), a [[filter (computer science)|filter]].


Each character in a regular expression is either understood to be a [[metacharacter]] with its special meaning, or a regular character with its literal meaning. Together, they can be used to identify textual material of a given pattern, or process a number of instances of it that can vary from a precise equality to a very general similarity of the pattern. The pattern sequence itself is an expression that is a statement in a language designed specifically to represent prescribed targets in the most concise and flexible way to direct the automation of [[text processing]] of general text files, specific textual forms, or of random input strings.
Feel free to visit my weblog :: [http://punterpedia.com/wiki/How_To_Find_Out_Everything_There_Is_To_Know_About_Nya_Internet_Svenska_Casinon_P%C3%A5_N%C3%A4tet_In_4_Simple_Steps nya internet casino]
 
A very simple use of a regular expression would be to locate the same word spelled two different ways in a text editor, for example <source lang="pcre" enclose="none">seriali[sz]e</source>. A [[Wildcard character|wildcard]] match can also achieve this, but wildcard matches differ from regular expressions in that wildcards are limited to what they can pattern (having fewer metacharacters and a simple language-base), whereas regular expressions are not. A usual context of [[wildcard character]]s is in [[glob (programming)|globbing]] similar names in a list of files, whereas regular expressions are usually employed in applications that pattern-match text strings in general. For example, the simple regexp {{nowrap|<source lang="pcre" enclose="none">^[ \t]+|[ \t]+$</source>}} matches excess whitespace at the beginning and end of a line. An advanced regexp used to match any numeral is <source lang="pcre" enclose="none">^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$ </source>.  See ''[[#Examples|Examples]]'' for more examples.
 
[[File:Thompson-kleene-star.svg|right|thumb|The [[Kleene star]]: "zero or more".]]
A '''regular expression processor''' processes a regular expression statement  expressed in terms of a grammar in a given [[Formal language#Programming languages|formal language]], and with that examines the target text string, [[Compiler-compiler|parsing]] it to identify substrings that are members of its language, the regular expressions.
 
Regular expressions are so useful in computing that the various systems to specify regular expressions have evolved to provide both a ''basic'' and ''extended'' standard for the grammar and syntax;  ''modern'' regular expressions heavily augment the standard. Regular expression processors are found in several [[search engine]]s, search and replace dialogs of several [[word processor]]s and [[text editor]]s, and in the command lines of [[:Category:Unix text processing utilities|text processing utilities]], such as [[sed]] and [[AWK]].
 
Many [[programming language]]s provide regular expression capabilities, some built-in, for example [[Perl language structure#Regular expressions|Perl]], [[Ruby (programming language)|Ruby]], [[AWK]], and [[Tcl]], and others via a [[standard library]], for example [[.NET Framework|.NET languages]], [[Java (programming language)|Java]], [[Python (programming language)|Python]] and [[C++]] (since [[C++11]]).
Most other languages offer regular expressions via a library.
 
==History==
Regular expressions originated in 1956, when mathematician [[Stephen Cole Kleene]] described [[regular language]]s using his mathematical notation called ''regular sets''.{{sfn|Kleene|1956}} These arose in [[theoretical computer science]], in the subfields of [[automata theory]] (models of computation) and the description and classification of [[formal language]]s. Other early implementations of [[pattern matching]] include the [[SNOBOL]] language, which did not use regular expressions, but instead its own syntax.
 
Regular expressions entered popular use from 1968 in two uses: pattern matching in a text editor{{sfn|Thompson|1968}} and lexical analysis in a compiler.{{sfn|Johnson|Porter|Ackley|Ross|1968}} Among the first appearances of regular expressions in program form was when [[Ken Thompson]] built Kleene's notation into the editor [[QED (text editor)|QED]] as a means to match patterns in [[text file]]s.{{sfn|Thompson|1968}}<ref name='Beautiful Code Kernighan'>{{cite book | last1 = Kernighan | first1 = Brian | authorlink1 = Brian Kernighan | title = Beautiful Code | chapter = A Regular Expressions Matcher | publisher = [[O'Reilly Media]] | pages = 1–2 | url = http://www.cs.princeton.edu/courses/archive/spr09/cos333/beautiful.html | accessdate = 2013-05-15 | isbn = 978-0-596-51004-6}}</ref><ref>{{cite web |url=http://cm.bell-labs.com/who/dmr/qed.html |title=An incomplete history of the QED Text Editor|last1=Ritchie |first1=Dennis M. |publisher= |accessdate=9 October 2013}}</ref>{{sfn|Aho|Ullman|1992|loc=10.11 Bibliographic Notes for Chapter 10, p. 589}} For speed, Thompson implemented regular expression matching by [[just-in-time compilation]] (JIT) to [[IBM 7094]] code on the [[Compatible Time-Sharing System]], an important early example of JIT compilation.{{sfn|Aycock|2003|loc=2. JIT Compilation Techniques, 2.1 Genesis, p. 98}} He later added this capability to the Unix editor [[ed (text editor)|ed]], which eventually led to the popular search tool [[grep]]'s use of regular expressions ("grep" is a word derived from the command for regular expression searching in the ed editor: <code>g/''re''/p</code> meaning "Global search for Regular Expression and Print matching lines"<ref>{{cite web | url=http://catb.org/jargon/html/G/grep.html | title=Jargon File 4.4.7: grep  | author=[[Eric S. Raymond|Raymond, Eric S.]] citing [[Dennis Ritchie]] | year=2003}}</ref>). 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.{{sfn|Johnson|Porter|Ackley|Ross|1968}}
 
Many variations of these original forms of regular expressions were used in [[Unix]]{{sfn|Aho|Ullman|1992|loc=10.11 Bibliographic Notes for Chapter 10, p. 589}} programs at [[Bell Labs]] in the 1970s, including [[vi]], [[Lex programming tool|lex]], [[sed]], [[AWK]], and [[expr]], and in other programs such as [[Emacs]]. Regular expressions were subsequently adopted by a wide range of programs, with these early forms standardized in the [[POSIX.2]] standard in 1992.
 
In the 1980s more complicated regular expressions arose in [[Perl]], which originally derived from a regex library written by [[Henry Spencer]] (1986), who later wrote an implementation of ''Advanced Regular Expressions'' for [[Tcl]].<ref>{{cite web | url = http://www.tcl.tk/doc/howto/regexp81.html | title = New Regular Expression Features in Tcl 8.1 | accessdate = 2013-10-11}}</ref> The Tcl library is a hybrid [[Nondeterministic finite automaton|NFA]]/[[Deterministic finite automaton|DFA]] implementation with improved performance characteristics, earning praise from [[Jeffrey Friedl]] who said, "...it really seems quite wonderful."<ref>{{cite book | last1 = Friedl | first1 = Jeffrey | authorlink = Jeffrey Friedl | title = Mastering Regular Expressions | chapter = The Mechanics of Expression Processing | publisher = [[O'Reilly Media]] | pages = 182 | isbn = 0-596-52812-4}}</ref> Software projects that have adopted Spencer's Tcl regular expression implementation include [[PostgreSQL]].<ref>{{cite web | url = http://www.postgresql.org/docs/9.3/interactive/functions-matching.html | title = PostgreSQL 9.3.1 Documentation: 9.7. Pattern Matching | accessdate = 2013-10-12}}</ref> Perl later expanded on Spencer's original library to add many new features,<ref>{{cite web | url=http://perldoc.perl.org/perlre.html | title=perlre: Perl regular expressions | author=[[Larry Wall|Wall, Larry]] and the Perl 5 development team | year=2006}}</ref> but has not yet caught up with Spencer's Advanced Regular Expressions implementation in terms of performance or [[Unicode]] handling.<ref>{{cite web | url= http://perldoc.perl.org/perlreguts.html#Unicode-and-Localisation-Support | title = http://perldoc.perl.org/perlreguts.html#Unicode-and-Localisation-Support | accessdate = 2013-10-11}}</ref><ref>{{cite web | url = http://swtch.com/~rsc/regexp/regexp1.html | title = Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby, ...) | author = Russ Cox | year = 2007 | accessdate = 2013-10-11}}</ref> Part of the effort in the design of [[Perl 6]] is to improve Perl's regular expression integration, and to increase their scope and capabilities to allow the definition of [[parsing expression grammar]]s.<ref name="Apocalypse5">{{harvtxt|Wall|2002}}</ref> The result is a [[mini-language]] called [[Perl 6 rules]], which are used to define Perl 6 grammar as well as provide a tool to programmers in the language. These rules maintain existing features of Perl 5.x regular expressions, but also allow [[Backus–Naur form|BNF]]-style definition of a [[recursive descent parser]] via sub-rules.
 
The use of regular expressions in structured information standards for document and database modeling started in the 1960s and expanded in the 1980s when industry standards like [[Standard Generalized Markup Language|ISO SGML]] (precursored by ANSI "GCA 101-1983") consolidated. The kernel of the [[XML schema#Validation|structure specification language]] standards consists of regular expressions. Its use is evident in the [[Document Type Definition|DTD]] element group syntax.
 
Starting in 1997, [[Philip Hazel]] developed [[Perl Compatible Regular Expressions|PCRE]] (Perl Compatible Regular Expressions), which attempts to closely mimic Perl's regular expression functionality and is used by many modern tools including [[PHP]] and [[Apache HTTP Server]].
 
Today regular expressions are widely supported in programming languages, text processing programs (particular lexers), advanced text editors, and some other programs. Regular expression support is part of the [[standard library]] of many programming languages, including [[Java (programming language)|Java]] and [[Python (programming language)|Python]], and is built into the syntax of others, including Perl and [[ECMAScript]]. Implementations of regular expression functionality is often called a '''regular expression engine''', and a number of libraries are available for reuse.
 
==Basic concepts==
A regular expression, often called a '''pattern''', is an expression used to specify a [[Set (computer science)|set]] of strings required for a particular purpose. A simple way to specify a set of strings is simply to list its [[Data element|elements]] or members. However, there are often more concise ways to specify the desired set of strings. For example, the set containing the three strings "Handel", "Händel", and "Haendel" can be specified by the '''pattern''' <code>H(ä|ae?)ndel</code>; we say that this pattern '''matches''' each of the three strings. In most [[formalism (mathematics)|formalism]]s, if there exists at least one regex that matches a particular set then there exists an infinite number of other regex that also match it—the specification is not unique. Most formalisms provide the following operations to construct regular expressions.
 
;Boolean "or"
:A [[vertical bar]] separates alternatives. For example, <code>gray|grey</code> can match "gray" or "grey".
;Grouping
:[[Bracket|Parentheses]] are used to define the scope and precedence of the [[Operator (programming)|operators]] (among other uses). For example, <code>gray|grey</code> and <code>gr(a|e)y</code> are equivalent patterns which both describe the set of "gray" or "grey".
;[[Quantification]]
:A [[quantifier]] after a [[Lexical_analysis#Token|token]] (such as a character) or group specifies how often that preceding element is allowed to occur. The most common quantifiers are the [[question mark]] <code>?</code>, the [[asterisk]] <code>*</code> (derived from the [[Kleene star]]), and the [[plus sign]] <code>+</code> ([[Kleene plus|Kleene cross]]).
:{|
|- style="vertical-align:top;"
|style="width:15px;"|<code>'''?'''</code>
|The question mark indicates there is ''zero or one'' of the preceding element. For example, <code><!--DON'T CHANGE THIS TO "colo?r"! REGULAR EXPRESSIONS DON'T WORK LIKE WILDCARDS!-->colou?r</code> matches both "color" and "colour".
|- style="vertical-align:top;"
|<code>'''<nowiki>*</nowiki>'''</code>
|The asterisk indicates there is ''zero or more'' of the preceding element. For example, <code>ab*c</code> matches "ac", "abc", "abbc", "abbbc", and so on.
|- style="vertical-align:top;"
|<code>'''+'''</code>
|The plus sign indicates there is ''one or more'' of the preceding element. For example, <code>ab+c</code> matches "abc", "abbc", "abbbc", and so on, but not "ac".
|}
 
These constructions can be combined to form arbitrarily complex expressions, much like one can construct arithmetical expressions from numbers and the operations '''+''', '''−''', '''×''', and '''÷'''. For example, <code>H(ae?|ä)ndel</code> and <code>H(a|ae|ä)ndel</code> are both valid patterns which match the same strings as the earlier example, <code>H(ä|ae?)ndel</code>.
 
The precise [[syntax]] for regular expressions varies among tools and with context; more detail is given in the [[#Syntax|''Syntax'' section]].
 
==Formal language theory==
Regular expressions describe [[regular language]]s in [[Formal language|formal language theory]]. They have the same expressive power as [[regular grammar]]s.
 
===Formal definition===
Regular expressions consist of constants and operator symbols that denote sets of strings and operations over these sets, respectively. The following definition is standard, and found as such in most textbooks on formal language theory.<ref name="HopcroftMotwaniUllman01">{{harvtxt|Hopcroft|Motwani|Ullman|2000}}</ref><ref>{{harvtxt|Sipser|1998}}</ref> Given a finite [[alphabet (computer science)|alphabet]] Σ, the following constants are defined
as regular expressions:
*(''empty set'') {{Unicode|∅}} denoting the set {{Unicode|∅}}.
*(''[[empty string]]'') ε denoting the set containing only the "empty" string, which has no characters at all.
*(''[[string literal|literal character]]'') ''<code>a</code>'' in Σ denoting the set containing only the character ''a''.
 
Given regular expressions R and S, the following operations over them are defined
to produce regular expressions:
* (''[[concatenation]]'') ''RS'' denotes the set of strings that can be obtained by concatenating a string in R and a string in S. For example {"ab", "c"}{"d", "ef"} = {"abd", "abef", "cd", "cef"}.
*(''[[alternation (formal language theory)|alternation]]'') ''R'' | ''S'' denotes the [[set union]] of sets described by ''R'' and ''S''. For example, if R describes {"ab", "c"} and S describes {"ab", "d", "ef"}, expression ''R'' | ''S'' describes {"ab", "c", "d", "ef"}.
*(''[[Kleene star]]'') ''R''* denotes the smallest [[subset|superset]] of set described by ''R'' that contains ε and is [[Closure (mathematics)|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 set described by ''R''. For example, {"0","1"}* is the set of all finite [[binary string]]s (including the empty string), and {"ab", "c"}* = {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", "abcab", ... }.
 
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, <code>(ab)c</code> can be written as <code>abc</code>, and <code>a|(b(c*))</code> can be written as <code>a|bc*</code>.
Many textbooks use the symbols {{Unicode|∪}}, {{Unicode|+}}, or {{Unicode|∨}} for alternation instead of the vertical bar.
 
'''Examples:'''
*<code>a|b*</code> denotes {ε, "a", "b", "bb", "bbb", ...}
*<code>(a|b)*</code> denotes the set of all strings with no symbols other than "a" and "b", including the empty string: {ε, "a", "b", "aa", "ab", "ba", "bb", "aaa", ...}
*<code>ab*(c|ε)</code> denotes the set of strings starting with "a", then zero or more "b"s and finally optionally a "c": {"a", "ac", "ab", "abc", "abb", "abbc", ...}
 
===Expressive power and compactness===
 
The formal definition of regular expressions is purposely parsimonious and avoids defining the redundant quantifiers <code>?</code> and <code>+</code>, which can be expressed as follows: <code>a+</code> = <code>aa*</code>, and <code>a?</code> = <code>(a|ε)</code>. Sometimes the [[set complement|complement]] operator is added, to give a ''generalized regular expression''; here ''R<sup>c</sup>'' matches all strings over Σ* that do not match ''R''. In principle, the complement operator is redundant, as it can always be circumscribed by using the other operators. However, the process for computing such a representation is complex, and the result may require expressions of a size that is [[Double exponential function|double exponentially]] larger.<ref>{{harvtxt|Gelade|Neven|2008}}</ref><ref>{{harvtxt|Gruber|Holzer|2008}}</ref>
 
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 [[exponential growth|exponentially]] in the size of the shortest equivalent regular expressions. The standard example here is the languages
''L<sub>k</sub>'' consisting of all strings over the alphabet {''a'',''b''} whose ''k<sup>th</sup>''-from-last letter equals&nbsp;''a''. On one hand, a regular expression describing ''L''<sub>4</sub> is given by <math>(a|b)^*a(a|b)(a|b)(a|b)</math>. Generalizing this pattern to ''L<sub>k</sub>'' gives the expression
 
:<math>(a|b)^*a\underbrace{(a|b)(a|b)\cdots(a|b)}_{k-1\text{ times}}. \, </math>
 
On the other hand, it is known that every deterministic finite automaton accepting the language ''L<sub>k</sub>'' must have at least 2<sup>''k''</sup> states. Luckily, there is a simple mapping from regular expressions to the more general [[nondeterministic finite automata]] (NFAs) that does not lead to such a blowup in size; for this reason NFAs are often used as alternative representations of regular languages. NFAs are a simple variation of the type-3 [[formal grammar|grammars]] of the [[Chomsky hierarchy]].<ref name="HopcroftMotwaniUllman01"/>
 
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; see [[#Patterns for non-regular languages|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]] which for two given regular expressions decides whether the described languages are essentially equal, reduces each expression to a minimal deterministic finite state machine, and determines whether they are [[isomorphism|isomorphic]] (equivalent).
 
The redundancy can be eliminated by using [[Kleene star]] and [[Union (set theory)|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 with [[Kleene algebra]].<ref>{{harvtxt|Kozen|1991}}</ref>
 
==Syntax==
<!-- header linked from Google Codesearch FAQ, please do not change -->
A regexp ''pattern'' matches a target ''string''. The pattern is composed of a sequence of ''atoms''.  An atom is what matches at a point in the target string.  The simplest atom is a literal, but grouping parts of the pattern to match an atom will require using <code>(&nbsp;)</code> as metacharacters. Metacharacters help form: ''atoms''; ''quantifiers'' telling how many atoms (and whether it is a ''greedy'' quantifier or not); a logical OR character, which offers a set of alternatives, and a logical NOT character, which negates an atom's existence; and back references 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 regular expression 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 regexp processor there are about fourteen metacharacters, characters that may or may not have their [[literal (computer programming)|literal]] character meaning, depending on context, or whether they are "escaped", ''i.e.'', preceded by an [[escape sequence]], in this case, the backslash <code>\</code>.  Modern and POSIX extended regular expressions use metacharacters more often than their literal meaning, so to avoid "backslash-osis" 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 <code>(&nbsp;)</code> and <code>{&nbsp;}</code> be primarily literal, and "escape" that usual meaning to become metacharacters. Common standards implement both. The usual metacharacters are <code> {}[]()^$.|*+?</code> and <code>\</code>. The usual characters that become metacharacters when escaped are <code>dsw.DSW</code> and <code>N</code>.
 
===Delimiters===
When entering a regular expression 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 regular expression <code>re</code> is entered as <code>"re"</code>. However, they are often written with slashes as [[delimiter]]s, as in <code>/re/</code> for the regular expression <code>re</code>. This originates in ed, where <code>/</code> is the editor command for searching, and an expression <code>/re/</code> can be used to specify a range of lines (matching the pattern), which can be combined with other commands on either side, most famously <code>g/re/p</code> as in [[grep]] ("global regex print"). A similar convention is used in [[sed]], where search and replace is given by <code>s/regexp/replacement/</code> and patterns can be joined with a comma to specify a range of lines as in <code>/re1/,/re2/</code>. This notation is particularly well-known due to its use in [[Perl]], where it forms part of the syntax distinct from normal string literals. In some cases, such as sed and Perl, alternative delimiters can be used to avoid collision with contents, and to avoid having to escape occurrences of the delimiter character in the contents. For example, in sed the command <code>s,/,X,</code> will replace a <code>/</code> with an <code>X</code>, using commas as delimiters.
 
===Standards===
 
The [[Institute of Electrical and Electronics Engineers|IEEE]] [[POSIX]] standard has three sets of compliance: BRE,<ref>ISO/IEC 9945-2:1993 ''Information technology – Portable Operating System Interface (POSIX) – Part 2: Shell and Utilities'', successively revised as ISO/IEC 9945-2:2002 ''Information technology – Portable Operating System Interface (POSIX) – Part 2: System Interfaces'', ISO/IEC 9945-2:2003, and currently ISO/IEC/IEEE 9945:2009 ''Information technology – Portable Operating System Interface (POSIX®) Base Specifications, Issue 7''</ref> ERE, and SRE for Basic, Extended, and Simple Regular Expressions. SRE is [[deprecated]],<ref>The Single Unix Specification (Version 2)</ref> in favor of BRE, as both provide backward compatibility.  The subsection below covering the ''character classes'' applies to both BRE and ERE.
 
BRE and ERE work together. ERE adds <code>?</code>, <code>+</code>, and  <code>|</code>, and it removes the need to escape the metacharacters <code>(&nbsp;)</code> and <code>{&nbsp;}</code>, which are ''required'' in BRE. Furthermore, as long as the POSIX standard syntax for regular expressions 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 Perl regular expressions.
 
[[Perl]] regular expressions have become a ''de facto'' standard, having a rich and powerful set of atomic expressions. Perl has no "basic" "extended" level, where the <code>(&nbsp;)</code> and <code>{&nbsp;}</code> may or may not have literal meanings.  They are always metacharacters, as they are in "extended" mode for POSIX.  To get their ''literal'' meaning, you escape them. Other metacharacters are known to be literal or symbolic based on context alone. Perl offers much more functionality: "lazy" regular expressions, [[backtracking]], named capture groups, and [[Recursion (computer science)|recursive]] patterns, all of which are powerful additions to POSIX BRE/ERE. (See [[#Lazy quantification|lazy quantification]] below.)
 
====POSIX basic and extended====
In the [[POSIX]] standard, Basic Regular Syntax, BRE, requires that the [[metacharacter]]s <code>(&nbsp;)</code> and <code>{&nbsp;}</code> be designated <code>\(\)</code> and <code>\{\}</code>, whereas Extended Regular Syntax, ERE, does not.
{| class="wikitable"
|-
! Metacharacter
! Description
|- valign="top"
!<code>.</code>
|Matches any single character (many applications exclude [[newline]]s, and exactly which characters are considered newlines is flavor-, character-encoding-, and platform-specific, but it is safe to assume that the line feed character is included). Within POSIX bracket expressions, the dot character matches a literal dot. For example, <code>a.c</code> matches "abc", etc., but <code>[a.c]</code> matches only "a", ".", or "c".
|- valign="top"
!<code>[&nbsp;]</code>
|A bracket expression. Matches a single character that is contained within the brackets. For example, <code>[abc]</code> matches "a", "b", or "c". <code>[a-z]</code> specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: <code>[abcx-z]</code> matches "a", "b", "c", "x", "y", or "z", as does <code>[a-cx-z]</code>.
The <code>-</code> character is treated as a literal character if it is the last or the first (after the <code>^</code>, if present) character within the brackets: <code>[abc-]</code>, <code>[-abc]</code>.  Note that backslash escapes are not allowed.  The <code>]</code> character can be included in a bracket expression if it is the first (after the <code>^</code>) character: <code>[]abc]</code>.
|- valign="top"
!<code>[^&nbsp;]</code>
|Matches a single character that is not contained within the brackets. For example, <code>[^abc]</code> matches any character other than "a", "b", or "c". <code>[^a-z]</code> matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed.
|- valign="top"
!<code>^</code>
|Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
|- valign="top"
!<code>$</code>
|Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, it matches the ending position of any line.
|- valign="top"
!<code>( )</code>
|Defines a marked subexpression. The string matched within the parentheses can be recalled later (see the next entry, <code>\''n''</code>).  A marked subexpression is also called a block or capturing group.  '''BRE mode requires {{nowrap|<code>\(&nbsp;\)</code>}}'''.
|- valign="top"
!<code>\''n''</code>
|Matches what the ''n''th 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.
|- valign="top"
!<code>*</code>
|Matches the preceding element zero or more times. For example, <code>ab*c</code> matches "ac", "abc", "abbbc", etc. <code>[xyz]*</code> matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. <code>(ab)*</code> matches "", "ab", "abab", "ababab", and so on.
|- valign="top"
!{{nowrap|<code>{''m'',''n''}</code>}}
|Matches the preceding element at least ''m'' and not more than ''n'' times. For example, <code>a{3,5}</code> matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regular expressions. '''BRE mode requires <code>{{nowrap|\{''m'',''n''\}}}</code>'''.
|}
 
'''Examples:'''
*<code>.at</code> matches any three-character string ending with "at", including "hat", "cat", and "bat".
*<code>[hc]at</code> matches "hat" and "cat".
*<code>[^b]at</code> matches all strings matched by <code>.at</code> except "bat".
*<code>[^hc]at</code> matches all strings matched by <code>.at</code> other than "hat" and "cat".
*<code>^[hc]at</code> matches "hat" and "cat", but only at the beginning of the string or line.
*<code>[hc]at$</code> matches "hat" and "cat", but only at the end of the string or line.
*<code>\[.\]</code> matches any single character surrounded by "[" and "]" since the brackets are escaped, for example: "[a]" and "[b]".
 
====POSIX extended====
The meaning of metacharacters [[escape sequence|escaped]] with a backslash is reversed for some characters in the POSIX Extended Regular Expression (ERE) syntax. With this syntax, a backslash causes the metacharacter to be treated as a literal character. So, for example, <code>\(&nbsp;\)</code> is now <code>(&nbsp;)</code> and <code>\{&nbsp;\}</code> is now <code>{&nbsp;}</code>. Additionally, support is removed for <code>\''n''</code> backreferences and the following metacharacters are added:
 
{| class="wikitable"
|-
! Metacharacter
! Description
|- valign="top"
!<code>?</code>
|Matches the preceding element zero or one time. For example, <code>ab?c</code> matches only "ac" or "abc".
|-
!<code>+</code>
|Matches the preceding element one or more times. For example, <code>ab+c</code> matches "abc", "abbc", "abbbc", and so on, but not "ac".
|-
!<code><nowiki>|</nowiki></code>
|The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, <code><nowiki>abc|def</nowiki></code> matches "abc" or "def".</td>
|}
 
'''Examples:'''
*<code>[hc]+at</code> matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".
*<code>[hc]?at</code> matches "hat", "cat", and "at".
*<code>[hc]*at</code> matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", "at", and so on.
*<code>cat|dog</code> matches "cat" or "dog".
 
POSIX Extended Regular Expressions can often be used with modern Unix utilities by including the [[command line]] flag <var>-E</var>.
 
====Character classes====
The character class is the most basic regular expression concept after a literal match.  It makes one small sequence of characters match a larger set of characters.  For example, <code>[A-Z]</code> could stand for the alphabet, and <code>\d</code> could mean any digit. Character classes apply to both POSIX levels.
 
When specifying a range of characters, such as <code>[a-Z]</code> 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 regular expression processor installed.  Those definitions are in the following table:
 
{| class="wikitable"
|-
! POSIX !! Non-standard !! Perl/Tcl !! Vim !! ASCII !! Description
|-
| <code>[:alnum:]</code>
|
|
|
| <code>[A-Za-z0-9]</code>
| Alphanumeric characters
|-
|
| <code>[:word:]</code>
| <code>\w</code>
| <code>\w</code>
| <code>[A-Za-z0-9_]</code>
| Alphanumeric characters plus "_"
|-
|
|
| <code>\W</code>
| <code>\W</code>
| <code>[^A-Za-z0-9_]</code>
| Non-word characters
|-
| <code>[:alpha:]</code>
|
|
| <code>\a</code>
| <code>[A-Za-z]</code>
| Alphabetic characters
|-
| <code>[:blank:]</code>
|
|
| <code>\s</code>
| <code>[ [[\t]]]</code>
| Space and tab
|-
|
|
| <code>\b</code>
| <code>\&lt; \&gt;</code>
| <code>(?<=\W)(?=\w)&#124;(?<=\w)(?=\W)</code>
| Word boundaries
|-
| <code>[:cntrl:]</code>
|
|
|
| <code>[\x00-\x1F\x7F]</code>
| [[Control character]]s
|-
| <code>[:digit:]</code>
|
| <code>\d</code>
| <code>\d</code>
| <code>[0-9]</code>
| Digits
|-
|
|
| <code>\D</code>
| <code>\D</code>
| <code>[^0-9]</code>
| Non-digits
|-
| <code>[:graph:]</code>
|
|
|
| <code>[\x21-\x7E]</code>
| Visible characters
|-
| <code>[:lower:]</code>
|
|
| <code>\l</code>
| <code>[a-z]</code>
| Lowercase letters
|-
| <code>[:print:]</code>
|
|
| <code>\p</code>
| <code>[\x20-\x7E]</code>
| Visible characters and the space character
|-
| <code>[:punct:]</code>
|
|
|
| <code><nowiki>[][!"#$%&'()*+,./:;<=>?@\^_`{|}~-]</nowiki></code>
| Punctuation characters
|-
| <code>[:space:]</code>
|
| <code>\s</code>
| <code>\_s</code>
| <code>[ [[\t]][[\r]][[\n]][[\v]][[\f]]]</code>
| [[Whitespace character]]s
|-
|
|
| <code>\S</code>
|
| <code>[^ \t\r\n\v\f]</code>
| Non-whitespace characters
|-
| <code>[:upper:]</code>
|
|
| <code>\u</code>
| <code>[A-Z]</code>
| Uppercase letters
|-
| <code>[:xdigit:]</code>
|
|
| <code>\x</code>
| <code>[A-Fa-f0-9]</code>
| Hexadecimal digits
|}
 
POSIX character classes can only be used within bracket expressions. For example, <code><nowiki>[[:upper:]ab]</nowiki></code> matches the uppercase letters and lowercase "a" and "b".
 
An additional non-POSIX class understood by some tools is <code>[:word:]</code>, which is usually defined as <code>[:alnum:]</code> plus underscore. This reflects the fact that in many programming languages these are the characters that may be used in identifiers. The editor [[Vim (text editor)|Vim]] further distinguishes ''word'' and ''word-head'' classes (using the notation <code>\w</code> and <code>\h</code>) since in many programming languages the characters that can begin an identifier are not the same as those that can occur in other positions.
 
Note that what the POSIX regular expression standards call ''character classes'' are commonly referred to as ''POSIX character classes'' in other regular expression flavors which support them. With most other regular expression flavors, the term ''character class'' is used to describe what POSIX calls ''bracket expressions''.
 
===Standard Perl===
The Perl standard is still evolving in Perl 6, but the current set of symbols and syntax has become a ''de facto'' standard.
 
Largely because of its expressive power, many other utilities and programming languages have adopted syntax similar to Perl's&nbsp;— for example, [[Java (programming language)|Java]], [[JavaScript]], [[Python (programming language)|Python]], [[Ruby (programming language)|Ruby]], [[Microsoft]]'s [[.NET Framework]], and the [[World Wide Web Consortium|W3C's]] [[XML Schema (W3C)|XML Schema]] all use regular expression syntax similar to Perl's. Some languages and tools such as [[Boost C++ Libraries|Boost]] and [[PHP]] support multiple regular expression flavors. Perl-derivative regular expression 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.<ref>{{cite web | url=http://perldoc.perl.org/perlre.html#PCRE%2fPython-Support | title= Perl Regular Expression Documentation |publisher=perldoc.perl.org | accessdate=January 8, 2012}}</ref>
 
===Lazy quantification===
Quantifiers match as many times as possible unless followed by <code>?</code>, when they match as few times as possible. If a quantifier is not followed by <code>?</code>, we say quantifier is ''[[Greedy algorithm|greedy]]''. For example, consider the string
 
Another whale sighting occurred on <January 26>, <2004>.
 
To match (then display) only "{{nowrap|<January 26>}}" and not "{{nowrap|, <2004>}}" it is tempting to write <code><.*></code>.  But there is more than one <big><code>></code></big>, and the expression can take the second one, and having both, still match, displaying {{nowrap|"<January 26>, <2004>}}". Because the <code>*</code> quantifier is greedy, it will consume as many characters as possible from the string, and "<nowiki><January 26>, <2004></nowiki>" has more characters than "<nowiki><January 26></nowiki>".
 
This problem can be avoided by specifying the text that is ''not'' to be matched: <code><nowiki><[^>]*></nowiki></code>), but modern regular expressions allow a quantifier to be specified as ''lazy''. They put a question mark after the quantifier to make it lazy <code><.*?></code>). By using a lazy quantifier, the expression tries the minimal match first. Lazy matching may also be used to improve performance by avoiding [[backtracking]] in cases when the longest match is likely to be incorrect.{{citation needed | reason=There appears to be some debate over the correct treatment of lazy matching and the entire subsection has no cited sources | date=February 2014}}
 
==Patterns for non-regular languages==
Many features found in modern regular expression libraries provide an expressive power that far exceeds the [[regular language]]s. For example, many implementations allow grouping subexpressions with parentheses and recalling the value they match in the same expression ('''{{visible anchor|backreferences}}''').  This means that, among other things, a pattern can match strings of repeated words like "papa" or "WikiWiki", called ''[[square (formal language theory)|square]]s'' in formal language theory. The pattern for these strings is <code>(.*)\1</code>.
 
The language of squares is not regular, nor is it [[context-free language|context-free]]. [[Pattern matching]] with an unbounded number of back references, as supported by numerous modern tools, is [[NP-complete]].<ref name="Aho90">see {{harvtxt|Aho|1990}} Theorem 6.2</ref>
 
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|formal language theory]] and pattern matching. For this reason, some people have taken to using the term ''regex'' or simply ''pattern'' to describe the latter. [[Larry Wall]], author of the Perl programming language, writes in an essay about the design of Perl 6:
 
{{cquote|'Regular expressions' [...] are only marginally related to real regular expressions. Nevertheless, the term has grown with the capabilities of our pattern matching engines, so I'm not going to try to fight linguistic necessity here. I will, however, generally call them "regexes" (or "regexen", when I'm in an Anglo-Saxon mood).<ref name="Apocalypse5"/>}}
 
==Fuzzy regular expressions==
{{unreferenced section|date=September 2011}}
Variants of regular expressions can be used for working with text in [[natural language]], when it is necessary to take into account possible typos and spelling variants. For example, the text "Julius Caesar" might be a fuzzy match for:
*Gaius Julius Caesar
*Yulius Cesar
*G. Juliy Caezar
In such cases the mechanism implements some [[Approximate string matching|fuzzy string matching]] algorithm and possibly some algorithm for finding the [[Edit distance|similarity]] between text fragment and pattern.
 
This task is closely related to both [[full text search]] and [[named entity recognition]].
 
Some [[Library (computing)|software libraries]] work with fuzzy regular expressions:
*[[TRE (computing)|TRE]] – well-developed portable free project in [[C (programming language)|C]], which uses syntax similar to [[#POSIX|POSIX]]
*FREJ – open source project in [[Java (programming language)|Java]] with non-standard syntax (which utilizes prefix, [[Lisp (programming language)|Lisp]]-like notation), targeted to allow easy use of substitutions of inner matched fragments in outer blocks, but lacks many features of standard regular expressions.
*[[agrep]] – command-line utility (proprietary, but free for non-commercial usage).
 
==Implementations and running times==
There are at least three different [[algorithm]]s that decide if and how a given regular expression matches a string.
 
The oldest and fastest relies on a result in formal language theory that allows every [[nondeterministic finite automaton]] (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 [[Big O notation|''O'']](''2<sup>m</sup>''), but it can be run on a string of size ''n'' in time ''O''(''n''). An alternative approach is to simulate the NFA directly, essentially building each DFA state on demand and then discarding it at the next step. This keeps the DFA implicit and avoids the exponential construction cost, but running cost rises to ''O''(''m n''). 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.<ref>
{{harvtxt|Cox|2007}}</ref><ref>{{harvtxt|Laurikari|2009}}</ref>
 
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 <code>(a|aa)*b</code> 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 [[ReDoS|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.
 
==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, regular expressions were originally written to use [[American Standard Code for Information Interchange|ASCII]] characters as their token set though regular expression libraries have supported numerous other [[character set]]s. Many modern regular expression 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 regular expressions to support Unicode.
 
* '''Supported encoding'''. Some regular expression 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 regular expression engines support only the [[Mapping of Unicode characters#Basic Multilingual Plane|Basic Multilingual Plane]], that is, the characters which can be encoded with only 16 bits. Currently, only a few regular expression 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 <code>[x-y]</code> are valid wherever ''x'' and ''y'' have [[code point]]s in the range [0x00,0x7F] and codepoint(''x'') ≤ codepoint(''y''). The natural extension of such character ranges to Unicode would simply change the requirement that the endpoints lie in [0x00,0x7F] to the requirement that they lie in [0,0x10FFFF]. However, in practice this is often not the case. Some implementations, such as that of [[Gawk (GNU package)|gawk]], do not allow character ranges to cross Unicode blocks. A range like [0x61,0x7F] is valid since both endpoints fall within the Basic Latin block, as is [0x0530,0x0560] since both endpoints fall within the Armenian block, but a range like [0x0061,0x0532] is invalid since it includes multiple Unicode blocks. Other engines, such as that of the [[Vim (text editor)|Vim]] editor, allow block-crossing but the character values must not be more than 256 apart.<ref>{{cite web|url=http://vimdoc.sourceforge.net/htmldoc/pattern.html#/%5B%5D |title=Vim documentation: pattern |publisher=Vimdoc.sourceforge.net |date= |accessdate=2013-09-25}}</ref>
* '''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 [[Devanāgarī|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 [[Unicode#Combining characters|combining characters]]. Like old typewriters, plain letters can be followed by one of more non-spacing symbols (usually diacritics like accent marks) 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 mark]]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.<ref name="unicode">{{cite web
| title = UTS#18 on Unicode Regular Expressions, Annex A: Character Blocks
| url = http://unicode.org/reports/tr18/#Character_Blocks
| accessdate = 2010-02-05}}</ref> In [[Perl]] and the {{Javadoc:SE|package=java.util.regex|java/util/regex}} library, properties of the form <code>\p{InX}</code> or <code>\p{Block=X}</code> match characters in block ''X'' and <code>\P{InX}</code> or <code>\P{Block=X}</code> matches code points not in that block. Similarly, <code>\p{Armenian}</code>, <code>\p{IsArmenian}</code>, or <code>\p{Script=Armenian}</code> matches any character in the Armenian script. In general, <code>\p{X}</code> matches any character with either the binary property ''X'' or the general category ''X''. For example, <code>\p{Lu}</code>, <code>\p{Uppercase_Letter}</code>, or <code>\p{GC=Lu}</code> matches any upper-case letter.  Binary properties that are ''not'' general categories include <code>\p{White_Space}</code>, <code>\p{Alphabetic}</code>, <code>\p{Math}</code>, and <code>\p{Dash}</code>. Examples of non-binary properties are <code>\p{Bidi_Class=Right_to_Left}</code>, <code>\p{Word_Break=A_Letter}</code>, and <code>\p{Numeric_Value=10}</code>.
 
==Uses==
Regular expressions are useful in the production of [[syntax highlighting]] systems, [[data validation]], and many other tasks.
 
While regular expressions would be useful on Internet [[Search engine (computing)|search engine]]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: [[Google Code Search]], [[Exalead]].
 
==Examples==
{{example farm|section|date=March 2012}}
 
A regular expression is a string that is used to describe or match a set of strings according to certain [[syntax]] rules. The specific syntax rules vary depending on the specific [[implementation]], [[programming language]], or [[Library (computing)|library]] in use. Additionally, the functionality of regex implementations can vary between [[Software versioning|version]]s.
 
Despite this variability, and because regular expressions can be difficult to both explain and understand without examples, this article provides a basic description of some of the properties of regular expressions by way of illustration.
 
The following conventions are used in the examples.<ref name="clarify000">The character 'm' is not always required to specify a [[Perl]] match operation. For example, <tt>m/[^abc]/</tt> could also be rendered as <tt>/[^abc]/</tt>. 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 '[http://perldoc.perl.org/perlre.html perldoc perlre]' for more details.</ref>
 
  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 regular expressions are all Perl-like syntax. Standard [[#POSIX Basic Regular Expressions|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 (e.g. basic vs. extended regex, <tt>\( \)</tt> vs. <tt>()</tt>, or lack of <tt>\d</tt> instead of [[POSIX]] <tt>[:digit:]</tt>).
 
The syntax and conventions used in these examples coincide with that of other programming environments as well.<ref>e.g., see ''[[Java (programming language)|Java]] [[O'Reilly Media#In a Nutshell|in a Nutshell]]''&nbsp;— Page 213, ''[[Python (programming language)|Python]] Scripting for Computational Science''&nbsp;— Page 320, Programming [[PHP]]&nbsp;— Page 106</ref>
 
{| class="wikitable"
! Meta-<br/>character(s)
! Description
! Example<ref>Note that all the if statements return a TRUE value</ref>
|-
! <tt>.</tt>
| Normally matches any character except a newline. <br/>Within square brackets the dot is literal.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/...../) {
  print "$string1 has length >= 5\n";
}
</source>
|-
! <tt>( )</tt>
| Groups a series of pattern elements to a single element. <br/>When you match a pattern within parentheses, you can use any of <tt>$1</tt>, <tt>$2</tt>, ... later to refer to the previously matched pattern.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/(H..).(o..)/) {
  print "We matched '$1' and '$2'\n";
}
</source>'''Output:'''<source lang="text" enclose="div">
We matched 'Hel' and 'o W'
</source>
|-
! <tt>+</tt>
| Matches the preceding pattern element one or more times.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/l+/) {
  print "There are one or more consecutive letter \"l\"'s in $string1\n";
}
</source>'''Output:'''<source lang="text" enclose="div">
There are one or more consecutive letter "l"'s in Hello World
</source>
|-
! <tt>?</tt>
| Matches the preceding pattern element zero or one times.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/H.?e/) {
  print "There is an 'H' and a 'e' separated by ";
  print "0-1 characters (Ex: He Hoe)\n";
}
</source>
|-
! <tt>?</tt>
| Modifies the <tt>*</tt>, <tt>+</tt>, or <tt>{M,N}</tt>'d regex that comes before to match as few times as possible.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/(l.+?o)/) {
  print "The non-greedy match with 'l' followed by one or\n";
  print "more characters is 'llo' rather than 'llo wo'.\n";
}
</source>'''Output:'''<source lang="text" enclose="div">
The non-greedy match with 'l' followed by one or
more characters is 'llo' rather than 'llo wo'.
</source>
|-
! <tt>*</tt>
| Matches the preceding pattern element zero or more times.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/el*o/) {
  print "There is an 'e' followed by zero to many ";
  print "'l' followed by 'o' (eo, elo, ello, elllo)\n";
}
</source>
|-
! {M,N}
| Denotes the minimum M and the maximum N match count.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/l{1,2}/) {
print "There exists a substring with at least 1 ";
 
print "and at most 2 l's in $string1\n";
}
</source>
|-
! <tt>[...]</tt>
| Denotes a set of possible character matches.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/[aeiou]+/) {
  print "$string1 contains one or more vowels.\n";
}
</source>
|-
! <tt><nowiki>|</nowiki></tt>
| Separates alternate possibilities.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/(Hello|Hi|Pogo)/) {
  print "At least one of Hello, Hi, or Pogo is ";
  print "contained in $string1.\n";
}
</source>
|-
! <tt>\b</tt>
| Matches a zero-width boundary between a word-class character (see next) and either a non-word class character or an edge.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/llo\b/) {
  print "There is a word that ends with 'llo'\n";
}
</source>
|-
! <tt>\w</tt>
| Matches an alphanumeric character, including "_"; <br/>same as <tt>[A-Za-z0-9_]</tt> in ASCII.  <br/>In Unicode<ref name="unicode" /> same as <tt style="white-space:normal;">[\p{Alphabetic}<wbr/>\p{GC=Mark}<wbr/>\p{GC=Decimal_Number}<wbr/>\p{GC=Connector_Punctuation}]</tt>, <br/>where the <tt>Alphabetic property</tt> contains more than just Letters, and the <tt>Decimal_Number</tt> property contains more than <tt>[0-9]</tt>.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/\w/) {
  print "There is at least one alphanumeric ";
  print "character in $string1 (A-Z, a-z, 0-9, _)\n";
}
</source>
|-
! <tt>\W</tt>
| Matches a '''non'''-alphanumeric character, excluding "_"; <br/>same as <tt>[^A-Za-z0-9_]</tt> in ASCII, <br/>and <tt style="white-space:normal;">[^\p{Alphabetic}<wbr/>\p{GC=Mark}<wbr/>\p{GC=Decimal_Number}<wbr/>\p{GC=Connector_Punctuation}]</tt> in Unicode.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/\W/) {
  print "The space between Hello and ";
  print "World is not alphanumeric\n";
}
</source>
|-
! <tt>\s</tt>
| Matches a whitespace character, <br/>which in ASCII are tab, line feed, form feed, carriage return, and space; <br/>in Unicode, also matches no-<wbr/>break spaces, next line, and the variable-<wbr/>width spaces (amongst others).
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/\s.*\s/) {
  print "There are TWO whitespace characters, which may";
  print " be separated by other characters, in $string1";
}
</source>
|-
! <tt>\S</tt>
| Matches anything BUT a whitespace.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/\S.*\S/) {
  print "There are TWO non-whitespace characters, which";
  print " may be separated by other characters, in $string1";
}
</source>
|-
! <tt>\d</tt>
| Matches a digit; <br/>same as <tt>[0-9]</tt> in ASCII; <br/>in Unicode, same as the <tt>\p{Digit}</tt> or <tt>\p{GC=Decimal_Number}</tt> property, which itself the same as the <tt>\p{Numeric_Type=Decimal}</tt> property.
|  <source lang="perl" enclose="div">
$string1 = "99 bottles of beer on the wall.";
if ($string1 =~ m/(\d+)/) {
  print "$1 is the first number in '$string1'\n";
}
</source>'''Output:'''<source lang="text" enclose="div">
99 is the first number in '99 bottles of beer on the wall.'
</source>
|-
! <tt>\D</tt>
| Matches a non-digit; <br/>same as <tt>[^0-9]</tt> in ASCII or <tt>\P{Digit}</tt> in Unicode.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/\D/) {
  print "There is at least one character in $string1";
  print " that is not a digit.\n";
}
</source>
|-
! <tt>^</tt>
| Matches the beginning of a line or string.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/^He/) {
  print "$string1 starts with the characters 'He'\n";
}
</source>
|-
! <tt>$</tt>
| Matches the end of a line or string.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/rld$/) {
  print "$string1 is a line or string ";
  print "that ends with 'rld'\n";
}
</source>
|-
! <tt>\A</tt>
| Matches the beginning of a string (but not an internal line).
|  <source lang="perl" enclose="div">
$string1 = "Hello\nWorld\n";
if ($string1 =~ m/\AH/) {
  print "$string1 is a string ";
  print "that starts with 'H'\n";
}
</source>
|-
! <tt>\z</tt>
| Matches the end of a string (but not an internal line).<ref name='Perl Best Practices'>{{cite book | last = Conway | first = Damian | authorlink = Damian Conway | title = Perl Best Practices | chapter = Regular Expressions, End of String | publisher = [[O'Reilly Media|O'Reilly]] | pages = 240 | url = http://www.scribd.com/doc/15491004/Perl-Best-Practices | year=2005 | isbn = 978-0-596-00173-5}}</ref>
|  <source lang="perl" enclose="div">
$string1 = "Hello\nWorld\n";
if ($string1 =~ m/d\n\z/) {
  print "$string1 is a string ";
  print "that ends with 'd\\n'\n";
}
</source>
|-
! <tt>[^...]</tt>
| Matches every character except the ones inside brackets.
|  <source lang="perl" enclose="div">
$string1 = "Hello World\n";
if ($string1 =~ m/[^abc]/) {
  print "$string1 contains a character other than ";
  print "a, b, and c\n";
}
</source>
|}
 
==See also==
*[[Comparison of regular expression engines]]
*[[Extended Backus–Naur Form]]
*[[List of regular expression software]] — applications which support regular expressions
*[[Regular tree grammar]]
 
==Notes==
{{Reflist|33em}}
 
==References==
{{Refbegin|33em}}
*{{Cite book
| last = Aho
| first = Alfred V.
| author-link =Alfred Aho
| year = 1990
| contribution = Algorithms for finding patterns in strings
| editor-last = van Leeuwen
| editor-first = Jan | editor-link = Jan van Leeuwen
| title = Handbook of Theoretical Computer Science, volume A: Algorithms and Complexity
| publisher = The MIT Press
| pages = 255–300
| ref = harv
| postscript = <!--None-->
}}
*{{Cite book
| last1 = Aho
| first1 = Alfred V.
| authorlink1 = Alfred Aho
| last2 = Ullman
| first2 = Jeffrey D.
| authorlink2 = Jeffrey Ullman
| year = 1992
| title = Foundations of Computer Science
| url = http://infolab.stanford.edu/~ullman/focs.html
| chapter = Chapter 10. Patterns, Automata, and Regular Expressions
| chapterurl = http://infolab.stanford.edu/~ullman/focs/ch10.pdf
}}
*{{Cite journal
| publisher = The Open Group
| url = http://pubs.opengroup.org/onlinepubs/007908799/xbd/re.html
| contribution = Regular Expressions
| title = The Single UNIX ® Specification, Version 2
| year = 1997
| ref = harv
| postscript = <!--None-->
}}
*{{Cite journal
| publisher = The Open Group
| url = http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html
| contribution = Chapter 9: Regular Expressions
| title = The Open Group Base Specifications Issue 6, IEEE Std 1003.1, 2004 Edition
| year = 2004
| ref = harv
| postscript = <!--None-->
}}
*{{cite web
| url = http://swtch.com/~rsc/regexp/regexp1.html
| title = Regular Expression Matching Can Be Simple and Fast
| last = Cox
| first = Russ
| year = 2007
| ref = harv
| postscript = <!--None-->}}
*{{cite book
| first = Ben
| last = Forta
| authorlink = Ben Forta
| year =2004
| title = Sams Teach Yourself Regular Expressions in 10 Minutes
| publisher = Sams
| isbn = 0-672-32566-7
}}
*{{cite book
| first = Jeffrey
| last = Friedl
| authorlink = Jeffrey Friedl
| year =2002
| title = Mastering Regular Expressions
| url = http://regex.info/
| publisher = [[O'Reilly Media|O'Reilly]]
| isbn = 0-596-00289-0
}}
*{{cite conference
| last1 = Gelade | first1 = Wouter
| last2 = Neven | first2 = Frank
| title = Succinctness of the Complement and Intersection of Regular Expressions
| pages = 325–336
| booktitle = Proceedings of the 25th International Symposium on Theoretical Aspects of Computer Science (STACS 2008)
| url = http://drops.dagstuhl.de/opus/volltexte/2008/1354
| year = 2008
| ref = harv
| postscript = <!--None-->}}
*{{cite book
| first = Jan
| last = Goyvaerts
| authorlink =
| coauthors = [Jan Goyvaerts], [Steven Levithan]
| year =2009
| title = Regular Expressions Cookbook
| publisher = [O'reilly]
| isbn = 978-0-596-52068-7
}}
*{{cite conference
| last1 = Gruber | first1 = Hermann
| last2 = Holzer | first2 = Markus
| title = Finite Automata, Digraph Connectivity, and Regular Expression Size
| pages = 39–50
| booktitle = Proceedings of the 35th International Colloquium on Automata, Languages and Programming (ICALP 2008)
| url = http://www.hermann-gruber.com/data/icalp08.pdf
| year = 2008
| doi = 10.1007/978-3-540-70583-3_4
| volume = 5126
| ref = harv
| postscript = <!--None-->
}}
*{{cite book
| first = Mehran
| last = Habibi
| year =2004
| title = Real World Regular Expressions with Java 1.4
| publisher = Springer
| isbn = 1-59059-107-0
}}
*{{cite book
  | last1 = Hopcroft
  | first1 = John E.
  | last2 = Motwani
  | first2 = Rajeev
  | last3 = Ullman
  | first3 = Jeffrey D.
  | title = Introduction to Automata Theory, Languages, and Computation
  | publisher = Addison-Wesley
  | year = 2000
  | edition = 2nd
  | ref = harv
}}
*{{cite doi|10.1145/364175.364185}}
*{{Cite book
|last = Kleene
|first = Stephen C.
|contribution = Representation of Events in Nerve Nets and Finite Automata
|title = Automata Studies
|editor1-last = Shannon
|editor1-first = Claude E.
|editor2-last = McCarthy
|editor2-first = John
|publisher = Princeton University Press
|year = 1956
|pages = 3–42
|ref = harv
|postscript = <!--None-->
}}
*{{Cite journal
|last = Kozen
|first = Dexter
|contribution = A Completeness Theorem for Kleene Algebras and the Algebra of Regular Events
|title = Proceedings of the 6th Annual IEEE Symposium on Logic in Computer Science (LICS 1991)
|pages = 214–225
|year = 1991
|ref = harv
|postscript = <!--None-->
}}
*{{cite web
| url=http://www.laurikari.net/tre/
| title = TRE library 0.7.6
| first = Ville
| last = Laurikari
| year = 2009
| ref = harv
}}
*{{cite book
| first = Francois
| last = Liger
| coauthors = Craig McQueen, Paul Wilton
| year =2002
| title = Visual Basic .NET Text Manipulation Handbook
| publisher = [[Wrox Press]]
| isbn = 1-86100-730-2
}}
*{{cite book
| first = Michael
| last = Sipser
| authorlink = Michael Sipser
| year =1998
| title = Introduction to the Theory of Computation
| chapter = Chapter 1: Regular Languages
| pages = 31–90
| publisher = PWS Publishing
| isbn = 0-534-94728-X
| ref = harv
}}
*{{cite book
| first = Tony
| last = Stubblebine
| year =2003
| title = Regular Expression Pocket Reference
| publisher = O'Reilly
| isbn = 0-596-00415-X
}}
*{{cite doi|10.1145/363347.363387}}
*{{cite web
| url=http://dev.perl.org/perl6/doc/design/apo/A05.html
| title=Apocalypse 5: Pattern Matching
| first=Larry
| last=Wall
| authorlink=Larry Wall
| year=2002
}}
{{Refend}}
 
==External links==
<!-- Please note: There are thousands of regex tools in existence. Since Wikipedia is not a repository of links (see [[WP:NOT]] and [[WP:LINKS]]), please do not add links to such resources. They will likely be removed. -->
{{wikibooks|Regular Expressions}}
{{Wikibooks
|1=R Programming
|2=Text Processing
}}
===Standards===
* ISO/IEC 9945-2:1993 [http://www.iso.org/iso/catalogue_detail.htm?csnumber=17841 ''Information technology – Portable Operating System Interface (POSIX) – Part 2: Shell and Utilities'']
* ISO/IEC 9945-2:2002 [http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=37313 ''Information technology – Portable Operating System Interface (POSIX) – Part 2: System Interfaces'']
* ISO/IEC 9945-2:2003 [http://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:2009 [http://www.iso.org/iso/iso_catalogue/catalogue_ics/catalogue_detail_ics.htm?csnumber=50516 ''Information technology – Portable Operating System Interface (POSIX®) Base Specifications, Issue 7'']
 
===Language references===
* [http://java.sun.com/docs/books/tutorial/essential/regex/index.html Java Tutorials: Regular Expressions]
* [http://perldoc.perl.org/perlre.html Perl Regular Expressions documentation]
* [http://msdn2.microsoft.com/en-us/library/ms974570.aspx VBScript and Regular Expressions]
* [http://msdn.microsoft.com/en-us/library/hs600312.aspx .NET Framework Regular Expressions]
* JavaScript [https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions Regular Expressions Chapter] and [https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp RegExp Object Reference] at the [[Mozilla Developer Center]]
 
===Links===
* {{dmoz|Computers/Programming/Languages/Regular_Expressions|Regular Expressions}}
* [http://billposer.org/Linguistics/Computation/Resources.html#patterns Pattern matching tools and libraries]
 
===Other===
* [http://doc.cat-v.org/bell_labs/structural_regexps/ Structural Regular Expressions], by Rob Pike
* [http://swtch.com/~rsc/regexp/ Implementing Regular Expressions], Russ Cox, including references to assist in reading {{harvtxt|Thompson|1968}}:
** [http://swtch.com/~rsc/regexp/ibm7094.html IBM 7094 Cheat Sheet], Russ Cox, November 2000 (updated January 2007)
** [http://swtch.com/~rsc/talks/regexp.pdf Implementing Regular Expressions], CS 121 Extra Lecture, November 17, 2000
 
{{DEFAULTSORT:Regular Expression}}
[[Category:Automata theory]]
[[Category:Formal languages]]
[[Category:Pattern matching]]
[[Category:Programming constructs]]
[[Category:Regular expressions]]

Revision as of 01:33, 4 March 2014

I would like to introduce myself to you, I am Natalie and I adore it. Delaware is where we've been residing for many years but my husband wants us to transfer. She is an workplace supervisor but she plans on altering it. Bottle tops collecting is the only hobby my wife doesn't approve of. See what's new on my web site right here: http://punterpedia.com/wiki/How_To_Find_Out_Everything_There_Is_To_Know_About_Nya_Internet_Svenska_Casinon_P%C3%A5_N%C3%A4tet_In_4_Simple_Steps

Feel free to visit my weblog :: nya internet casino