Regular Expression
The match results of the pattern
(?<=\.) {2,}(?=[A-Z])

At least two spaces are matched, but only if they occur directly after a period (.) and before an upper case letter.
Stephen Cole Kleene, who helped found the concept
A blacklist on Wikipedia which uses regular expressions to identify bad titles

A regular expression, regex or regexp[1] (sometimes called a rational expression)[2][3] is, in theoretical computer science and formal language theory, a sequence of characters that define a search pattern. Usually this pattern is then used by string searching algorithms for "find" or "find and replace" operations on strings.

The concept arose in the 1950s when the American mathematician Stephen Cole Kleene formalized the description of a regular language. The concept came into common use with Unix text-processing utilities. Since the 1980s, different syntaxes for writing regular expressions exist, one being the POSIX standard and another, widely used, being the Perl syntax.

Regular expressions are used in search engines, search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK and in lexical analysis. Many programming languages provide regex capabilities, built-in, or via libraries.

## Patterns

The phrase regular expressions (and consequently, regexes) is often used to mean the specific, standard textual syntax (distinct from the mathematical notation described below) for representing patterns that matching text need to conform to. Each character in a regular expression (that is, each character in the string describing its pattern) is understood to be a metacharacter (with its special meaning), or a regular character (with its literal meaning). For example, in the regex a. a is a literal character which matches just 'a' and . is a meta character which matches every character except a newline. Therefore, this regex would match for example 'a ' or 'ax' or 'a0'. Together, metacharacters and literal characters can be used to identify textual material of a given pattern, or process a number of instances of it. Pattern-matches can vary from a precise equality to a very general similarity (controlled by the metacharacters). For example, . is a very general pattern, [a-z] (match all letters from 'a' to 'z') is less general and a is a precise pattern (match just 'a'). The metacharacter syntax is designed specifically to represent prescribed targets in a concise and flexible way to direct the automation of text processing of a variety of input data, in a form easy to type using a standard ASCII keyboard.

A very simple case of a regular expression in this syntax would be to locate the same word spelled two different ways in a text editor, the regular expression seriali[sz]e matches both "serialise" and "serialize". Wildcards could also achieve this, but are more limited in what they can pattern (having fewer metacharacters and a simple language-base).

### Delimiters

When entering a regex in a programming language, they may be represented as a usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where the regex re is entered as "re". However, they are often written with slashes as delimiters, as in /re/ for the regex re. This originates in ed, where / is the editor command for searching, and an expression /re/ can be used to specify a range of lines (matching the pattern), which can be combined with other commands on either side, most famously g/re/p as in grep ("global regex print"), which is included in most Unix-based operating systems, such as Linux distributions. A similar convention is used in sed, where search and replace is given by s/re/replacement/ and patterns can be joined with a comma to specify a range of lines as in /re1/,/re2/. This notation is particularly well-known due to its use in Perl, where it forms part of the syntax distinct from normal string literals. In some cases, such as sed and Perl, alternative delimiters can be used to avoid collision with contents, and to avoid having to escape occurrences of the delimiter character in the contents. For example, in sed the command s,/,X, will replace a / with an X, using commas as delimiters.

### Standards

The IEEE POSIX standard has three sets of compliance: BRE (Basic Regular Expressions),[25] ERE (Extended Regular Expressions), and SRE (Simple Regular Expressions). SRE is deprecated,[26] in favor of BRE, as both provide backward compatibility. The subsection below covering the character classes applies to both BRE and ERE.

BRE and ERE work together. ERE adds ?, +, and |, and it removes the need to escape the metacharacters ( ) and { }, which are required in BRE. Furthermore, as long as the POSIX standard syntax for regexes is adhered to, there can be, and often is, additional syntax to serve specific (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 regexes.

Perl regexes have become a de facto standard, having a rich and powerful set of atomic expressions. Perl has no "basic" or "extended" levels, where the ( ) and { } 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" regexes, backtracking, named capture groups, and recursive patterns, all of which are powerful additions to POSIX BRE/ERE. (See lazy matching below.)

#### POSIX basic and extended

In the POSIX standard, Basic Regular Syntax (BRE) requires that the metacharacters ( ) and { } be designated  and \{\}, whereas Extended Regular Syntax (ERE) does not.

Metacharacter Description
^ Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
. Matches any single character (many applications exclude newlines, and exactly which characters are considered newlines is flavor-, character-encoding-, and platform-specific, but it is safe to assume that the line feed character is included). Within POSIX bracket expressions, the dot character matches a literal dot. For example, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c".
[ ] A bracket expression. Matches a single character that is contained within the brackets. For example, [abc] matches "a", "b", or "c". [a-z] specifies a range which matches any lowercase letter from "a" to "z". These forms can be mixed: [abcx-z] matches "a", "b", "c", "x", "y", or "z", as does [a-cx-z].

The - character is treated as a literal character if it is the last or the first (after the ^, if present) character within the brackets: [abc-], [-abc]. Note that backslash escapes are not allowed. The ] character can be included in a bracket expression if it is the first (after the ^) character: []abc].

[^ ] Matches a single character that is not contained within the brackets. For example, [^abc] matches any character other than "a", "b", or "c". [^a-z] matches any single character that is not a lowercase letter from "a" to "z". Likewise, literal characters and ranges can be mixed.
$ Matches the ending position of the string or the position just before a string-ending newline. In line-based tools, it matches the ending position of any line. ( ) Defines a marked subexpression. The string matched within the parentheses can be recalled later (see the next entry, \n). A marked subexpression is also called a block or capturing group. BRE mode requires . \n Matches what the nth marked subexpression matched, where n is a digit from 1 to 9. This construct is vaguely defined in the POSIX.2 standard. Some tools allow referencing more than nine capturing groups. * Matches the preceding element zero or more times. For example, ab*c matches "ac", "abc", "abbbc", etc. [xyz]* matches "", "x", "y", "z", "zx", "zyx", "xyzzy", and so on. (ab)* matches "", "ab", "abab", "ababab", and so on. Matches the preceding element at least m and not more than n times. For example, a{3,5} matches only "aaa", "aaaa", and "aaaaa". This is not found in a few older instances of regexes. BRE mode requires }. Examples: • .at matches any three-character string ending with "at", including "hat", "cat", and "bat". • [hc]at matches "hat" and "cat". • [^b]at matches all strings matched by .at except "bat". • [^hc]at matches all strings matched by .at other than "hat" and "cat". • ^[hc]at matches "hat" and "cat", but only at the beginning of the string or line. • [hc]at$ matches "hat" and "cat", but only at the end of the string or line.
• $.$ matches any single character surrounded by "[" and "]" since the brackets are escaped, for example: "[a]" and "[b]".
• s.* matches s followed by zero or more characters, for example: "s" and "saw" and "seed".

#### 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:

Metacharacter Description
? Matches the preceding element zero or one time. For example, ab?c matches only "ac" or "abc".
+ Matches the preceding element one or more times. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
| The choice (also known as alternation or set union) operator matches either the expression before or the expression after the operator. For example, abc|def matches "abc" or "def".

Examples:

• [hc]?at matches "hat", "cat", and "at".
• [hc]*at matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", "at", and so on.
• [hc]+at matches "hat", "cat", "hhat", "chat", "hcat", "cchchat", and so on, but not "at".
• cat|dog matches "cat" or "dog".

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

#### Character classes

The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z] could stand for the upper case alphabet, and \d could mean any digit. Character classes apply to both POSIX levels.

When specifying a range of characters, such as [a-Z] (i.e. lowercase a to upper-case 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 Non-standard Perl/Tcl Vim Java ASCII Description
[:ascii:][27] \p{ASCII} [\x00-\x7F] ASCII characters
[:alnum:] \p{Alnum} [A-Za-z0-9] Alphanumeric characters
[:word:][] \w \w \w [A-Za-z0-9_] Alphanumeric characters plus "_"
\W \W \W [^A-Za-z0-9_] Non-word characters
[:alpha:] \a \p{Alpha} [A-Za-z] Alphabetic characters
[:blank:] \s \p{Blank} [ [[\t]]] Space and tab
\b \< \> \b (?<=\W)(?=\w)|(?<=\w)(?=\W) Word boundaries
\B (?<=\W)(?=\W)|(?<=\w)(?=\w) Non-word boundaries
[:cntrl:] \p{Cntrl} [\x00-\x1F\x7F] Control characters
[:digit:] \d \d \p{Digit} or \d [0-9] Digits
\D \D \D [^0-9] Non-digits
[:graph:] \p{Graph} [\x21-\x7E] Visible characters
[:lower:] \l \p{Lower} [a-z] Lowercase letters
[:print:] \p \p{Print} [\x20-\x7E] Visible characters and the space character
[:punct:] \p{Punct} [][!"#$%&'*+,./:;<=>?@\^_{|}~-] Punctuation characters [:space:] \s \_s \p{Space} or \s [ \t\r\n\v\f] Whitespace characters \S \S \S [^ \t\r\n\v\f] Non-whitespace characters [:upper:] \u \p{Upper} [A-Z] Uppercase letters [:xdigit:] \x \p{XDigit} [A-Fa-f0-9] Hexadecimal digits POSIX character classes can only be used within bracket expressions. For example, [[:upper:]ab] matches the uppercase letters and lowercase "a" and "b". An additional non-POSIX class understood by some tools is [:word:], which is usually defined as [:alnum:] plus underscore. This reflects the fact that in many programming languages these are the characters that may be used in identifiers. The editor Vim further distinguishes word and word-head classes (using the notation \w and \h) since in many programming languages the characters that can begin an identifier are not the same as those that can occur in other positions. 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 Because of its expressive power and (relative) ease of reading, many other utilities and programming languages have adopted syntax similar to Perl's--for example, Java, JavaScript, Python, Ruby, Microsoft's .NET Framework, and XML Schema. Some languages and tools such as Boost and PHP support multiple regex flavors. Perl-derivative regex implementations are not identical and usually implement a subset of features found in Perl 5.0, released in 1994. Perl sometimes does incorporate features initially found in other languages, for example, Perl 5.10 implements syntactic extensions originally developed in PCRE and Python.[28] ### 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.[29] The regex ".*" applied to the string "Ganymede," he continued, "is the largest moon in the Solar System."  matches the entire line instead of matching only "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,".[29] However, this does not ensure that not the whole sentence is matched in some contexts. The question-mark operator does not change the meaning of the dot operator, so this still can match the quotes in the input. A pattern like ".*?" EOF will still match the whole input if this is the string "Ganymede," he continued, "is the largest moon in the Solar System." EOF  To ensure that the quotes cannot be part of the match, the dot has to be replaced, e. g. like this: "[^"]*" This will match a quoted text part without additional quotes in it. ### Possessive matching In Java, quantifiers may be made possessive by appending a plus sign, which disables backing off, even if doing so would allow the overall match to succeed:[30] 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 not match at all, 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. Possessive quantifiers are easier to implement than greedy and lazy quantifiers, and are typically more efficient at runtime.[30] ## Patterns for non-regular languages Many features found in virtually all modern regular expression libraries provide an expressive power that far exceeds the regular languages. For example, many implementations allow grouping subexpressions with parentheses and recalling the value they match in the same expression (backreferences). This means that, among other things, a pattern can match strings of repeated words like "papa" or "WikiWiki", called squares in formal language theory. The pattern for these strings is (.+)\1. The language of squares is not regular, nor is it context-free, due to the pumping lemma. However, pattern matching with an unbounded number of backreferences, as supported by numerous modern tools, is still context sensitive.[31] However, many tools, libraries, and engines that provide such constructions still use the term regular expression for their patterns. This has led to a nomenclature where the term regular expression has different meanings in formal language theory and pattern matching. For this reason, some people have taken to using the term regex, regexp, or simply pattern to describe the latter. Larry Wall, author of the Perl programming language, writes in an essay about the design of Perl 6: "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).[18] ## Fuzzy regexes Variants of regexes 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 fuzzy string matching algorithm and possibly some algorithm for finding the similarity between text fragment and pattern. This task is closely related to both full text search and named entity recognition. Some software libraries work with fuzzy regexes: • TRE - well-developed portable free project in C, which uses syntax similar to POSIX • FREJ - open source project in Java with non-standard syntax (which utilizes prefix, Lisp-like notation), targeted to allow easy use of substitutions of inner matched fragments in outer blocks, but lacks many features of standard regexes. • agrep - open source command-line utility. ## Implementations and running times There are at least three different algorithms that decide whether and how a given regex matches a string. The oldest and fastest relies on a result in formal language theory that allows every nondeterministic finite automaton (NFA) to be transformed into a deterministic finite automaton (DFA). The DFA can be constructed explicitly and then run on the resulting input string one symbol at a time. Constructing the DFA for a regular expression of size m has the time and memory cost of O(2m), 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(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.[32][33] 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 (a|aa)*b that contain both alternation and unbounded quantification and force the algorithm to consider an exponentially increasing number of sub-cases. This behavior can cause a security problem called Regular expression Denial of Service. Although backtracking implementations only give an exponential guarantee in the worst case, they provide much greater flexibility and expressive power. For example, any implementation which allows the use of backreferences, or implements the various extensions introduced by Perl, must include some kind of backtracking. Some implementations[which?] 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, regexes were originally written to use ASCII characters as their token set though regex libraries have supported numerous other character sets. Many modern regex engines offer at least some support for Unicode. In most respects it makes no difference what the character set is, but some issues do arise when extending regexes to support Unicode. • Supported encoding. Some regex libraries expect to work on some particular encoding instead of on abstract Unicode characters. Many of these require the UTF-8 encoding, while others might expect UTF-16, or UTF-32. In contrast, Perl and Java are agnostic on encodings, instead operating on decoded characters internally. • Supported Unicode range. Many regex engines support only the Basic Multilingual Plane, that is, the characters which can be encoded with only 16 bits. Currently, only a few regex engines (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 [x-y] are valid wherever x and y have code points in the range [0x00,0x7F] and codepoint(x) 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 [0x0000,0x10FFFF]. However, in practice this is often not the case. Some implementations, such as that of gawk, do not allow character ranges to cross Unicode blocks. A range like [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 editor, allow block-crossing but the character values must not be more than 256 apart.[34] • Case insensitivity. Some case-insensitivity flags affect only the ASCII characters. Other flags affect all characters. Some engines have two different flags, one for ASCII, the other for Unicode. Exactly which characters belong to the POSIX classes also varies. • Cousins of case insensitivity. As ASCII has case distinction, case insensitivity became a logical feature in text searching. Unicode introduced alphabetic scripts without case like Devanagari. For these, case sensitivity is not applicable. For scripts like Chinese, another distinction seems logical: between traditional and simplified. In Arabic scripts, insensitivity to initial, medial, final, and isolated position may be desired. In Japanese, insensitivity between hiragana and katakana is sometimes useful. • Normalization. Unicode has combining characters. Like old typewriters, plain letters can be followed by one or more non-spacing symbols (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 marks and text direction markers. These codes might have to be dealt with in a special way. • Introduction of character classes for Unicode blocks, scripts, and numerous other character properties. Block properties are much less useful than script properties, because a block can have code points from several different scripts, and a script can have code points from several different blocks.[35] In Perl and the java.util.regex library, properties of the form \p{InX} or \p{Block=X} match characters in block X and \P{InX} or \P{Block=X} matches code points not in that block. Similarly, \p{Armenian}, \p{IsArmenian}, or \p{Script=Armenian} matches any character in the Armenian script. In general, \p{X} matches any character with either the binary property X or the general category X. For example, \p{Lu}, \p{Uppercase_Letter}, or \p{GC=Lu} matches any upper-case letter. Binary properties that are not general categories include \p{White_Space}, \p{Alphabetic}, \p{Math}, and \p{Dash}. Examples of non-binary properties are \p{Bidi_Class=Right_to_Left}, \p{Word_Break=A_Letter}, and \p{Numeric_Value=10}. ## Uses Regexes are useful in a wide variety of text processing tasks, and more generally string processing, where the data need not be textual. Common applications include data validation, data scraping (especially web scraping), data wrangling, simple parsing, the production of syntax highlighting systems, and many other tasks. While regexes would be useful on Internet search engines, processing them across the entire database could consume excessive computer resources depending on the complexity and design of the regex. Although in many cases system administrators can run regex-based queries internally, most search engines do not offer regex support to the public. Notable exceptions: Google Code Search, Exalead. However, Google Code Search has been shut down as of March 2013.[36][better source needed] ## Examples The specific syntax rules vary depending on the specific implementation, programming language, or library in use. Additionally, the functionality of regex implementations can vary between versions. Because regexes can be difficult to both explain and understand without examples, interactive web sites 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.[37] 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 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,  vs. , or lack of \d instead of POSIX [:digit:]). The syntax and conventions used in these examples coincide with that of other programming environments as well.[38] Meta- character(s) Description Example[39] . Normally matches any character except a newline. Within square brackets the dot is literal. $string1 = "Hello World\n";
if ($string1 =~ m/...../) { print "$string1 has length >= 5.\n";
}


Output:

Hello World
has length >= 5.

( ) Groups a series of pattern elements to a single element.
When you match a pattern within parentheses, you can use any of $1, $2, ... later to refer to the previously matched pattern.
$string1 = "Hello World\n"; if ($string1 =~ m/(H..).(o..)/) {
print "We matched '$1' and '$2'.\n";
}


Output:

We matched 'Hel' and 'o W'.

+ Matches the preceding pattern element one or more times.
$string1 = "Hello World\n"; if ($string1 =~ m/l+/) {
print "There are one or more consecutive letter \"l\"'s in $string1.\n"; }  Output: There are one or more consecutive letter "l"'s in Hello World.  ? Matches the preceding pattern element zero or one time. $string1 = "Hello World\n";
if ($string1 =~ m/H.?e/) { print "There is an 'H' and a 'e' separated by "; print "0-1 characters (e.g., He Hue Hee).\n"; }  Output: There is an 'H' and a 'e' separated by 0-1 characters (e.g., He Hue Hee).  ? Modifies the *, +, ? or {M,N}'d regex that comes before to match as few times as possible. $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"; }  Output: The non-greedy match with 'l' followed by one or more characters is 'llo' rather than 'llo Wo'.  * Matches the preceding pattern element zero or more times. $string1 = "Hello World\n";
if ($string1 =~ m/el*o/) { print "There is an 'e' followed by zero to many "; print "'l' followed by 'o' (e.g., eo, elo, ello, elllo).\n"; }  Output: There is an 'e' followed by zero to many 'l' followed by 'o' (e.g., eo, elo, ello, elllo).  {M,N} Denotes the minimum M and the maximum N match count. N can be omitted and M can be 0: {M} matches "exactly" M times; {M,} matches "at least" M times; {0,N} matches "at most" N times. x* y+ z? is thus equivalent to x{0,} y{1,} z{0,1}. $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";
}


Output:

There exists a substring with at least 1 and at most 2 l's in Hello World

[...] Denotes a set of possible character matches.
$string1 = "Hello World\n"; if ($string1 =~ m/[aeiou]+/) {
print "$string1 contains one or more vowels.\n"; }  Output: Hello World contains one or more vowels.  | Separates alternate possibilities. $string1 = "Hello World\n";
if ($string1 =~ m/(Hello|Hi|Pogo)/) { print "$string1 contains at least one of Hello, Hi, or Pogo.";
}


Output:

Hello World
contains at least one of Hello, Hi, or Pogo.

\b Matches a zero-width boundary between a word-class character (see next) and either a non-word class character or an edge; same as

(^\w|\w$|\W\w|\w\W). $string1 = "Hello World\n";
if ($string1 =~ m/llo\b/) { print "There is a word that ends with 'llo'.\n"; }  Output: There is a word that ends with 'llo'.  \w Matches an alphanumeric character, including "_"; same as [A-Za-z0-9_] in ASCII, and [\p{Alphabetic}\p{GC=Mark}\p{GC=Decimal_Number}\p{GC=Connector_Punctuation}] in Unicode,[35] where the Alphabetic property contains more than Latin letters, and the Decimal_Number property contains more than Arab digits. $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";
}


Output:

There is at least one alphanumeric character in Hello World
(A-Z, a-z, 0-9, _).

\W Matches a non-alphanumeric character, excluding "_";
same as [^A-Za-z0-9_] in ASCII, and
[^\p{Alphabetic}\p{GC=Mark}\p{GC=Decimal_Number}\p{GC=Connector_Punctuation}]

in Unicode.

$string1 = "Hello World\n"; if ($string1 =~ m/\W/) {
print "The space between Hello and ";
print "World is not alphanumeric.\n";
}


Output:

The space between Hello and World is not alphanumeric.

\s Matches a whitespace character,
which in ASCII are tab, line feed, form feed, carriage return, and space;
in Unicode, also matches no-break spaces, next line, and the variable-width spaces (amongst others).
$string1 = "Hello World\n"; if ($string1 =~ m/\s.*\s/) {
print "In $string1 there are TWO whitespace characters, which may"; print " be separated by other characters.\n"; }  Output: In Hello World there are TWO whitespace characters, which may be separated by other characters.  \S Matches anything BUT a whitespace. $string1 = "Hello World\n";
if ($string1 =~ m/\S.*\S/) { print "In$string1 there are TWO non-whitespace characters, which";
print " may be separated by other characters.\n";
}


Output:

In Hello World
there are TWO non-whitespace characters, which may be separated by other characters.

\d Matches a digit;
same as [0-9] in ASCII;
in Unicode, same as the \p{Digit} or \p{GC=Decimal_Number} property, which itself the same as the \p{Numeric_Type=Decimal} property.
$string1 = "99 bottles of beer on the wall."; if ($string1 =~ m/(\d+)/) {
print "$1 is the first number in '$string1'\n";
}


Output:

99 is the first number in '99 bottles of beer on the wall.'

\D Matches a non-digit;
same as [^0-9] in ASCII or \P{Digit} in Unicode.
$string1 = "Hello World\n"; if ($string1 =~ m/\D/) {
print "There is at least one character in $string1"; print " that is not a digit.\n"; }  Output: There is at least one character in Hello World that is not a digit.  ^ Matches the beginning of a line or string. $string1 = "Hello World\n";
if ($string1 =~ m/^He/) { print "$string1 starts with the characters 'He'.\n";
}


Output:

Hello World
starts with the characters 'He'.

$ Matches the end of a line or string. $string1 = "Hello World\n";
if ($string1 =~ m/rld$/) {
print "$string1 is a line or string "; print "that ends with 'rld'.\n"; }  Output: Hello World is a line or string that ends with 'rld'.  \A Matches the beginning of a string (but not an internal line). $string1 = "Hello\nWorld\n";
if ($string1 =~ m/\AH/) { print "$string1 is a string ";
print "that starts with 'H'.\n";
}


Output:

Hello
World
is a string that starts with 'H'.

\z Matches the end of a string (but not an internal line).[40]
$string1 = "Hello\nWorld\n"; if ($string1 =~ m/d\n\z/) {
print "$string1 is a string "; print "that ends with 'd\\n'.\n"; }  Output: Hello World is a string that ends with 'd\n'.  [^...] Matches every character except the ones inside brackets. $string1 = "Hello World\n";
if ($string1 =~ m/[^abc]/) { print "$string1 contains a character other than ";
print "a, b, and c.\n";
}


Output:

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


## Induction

Regular expressions can often be created ("induced" or "learned") based on a set of example strings. This is known as the induction of regular languages, and is part of the general problem of grammar induction in computational learning theory. 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 {1, 10, 100}, and negative set (of counterexamples) {11, 1001, 101, 0} can be used to induce the regular expression 1?0* (1 followed by zero or more 0s).

## Notes

1. ^ What Regular Expressions Are Exactly - Terminology
2. ^ Ruslan Mitkov (2003). The Oxford Handbook of Computational Linguistics. Oxford University Press. p. 754. ISBN 978-0-19-927634-9.
3. ^ Mark V. Lawson (17 September 2003). Finite Automata. CRC Press. pp. 98-100. ISBN 978-1-58488-255-8.
4. ^
5. ^ a b
6. ^ a b
7. ^ Kernighan, Brian. "A Regular Expressions Matcher". Beautiful Code. O'Reilly Media. pp. 1-2. ISBN 978-0-596-51004-6. Retrieved .
8. ^ Ritchie, Dennis M. "An incomplete history of the QED Text Editor". Retrieved 2013.
9. ^ a b Aho & Ullman 1992, 10.11 Bibliographic Notes for Chapter 10, p. 589.
10. ^ Aycock 2003, 2. JIT Compilation Techniques, 2.1 Genesis, p. 98.
11. ^ Raymond, Eric S. citing Dennis Ritchie (2003). "Jargon File 4.4.7: grep".
12. ^ "New Regular Expression Features in Tcl 8.1". Retrieved .
13. ^ Friedl, Jeffrey. "The Mechanics of Expression Processing". Mastering Regular Expressions. O'Reilly Media. p. 182. ISBN 0-596-52812-4.
14. ^
15. ^ Wall, Larry and the Perl 5 development team (2006). "perlre: Perl regular expressions".
16. ^ "Unicode and Localisation Support". Retrieved .
17. ^ Russ Cox (2007). "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby, ...)". Retrieved .
18. ^ a b Wall (2002)
19. ^ a b c grep(1) man page
20. ^ a b Hopcroft, Motwani & Ullman (2000)
21. ^ Sipser (1998)
22. ^ Gelade & Neven (2008)
23. ^ Gruber & Holzer (2008)
24. ^
25. ^ 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
26. ^ The Single Unix Specification (Version 2)
27. ^ "33.3.1.2 Character Classes -- Emacs lisp manual -- Version 25.1". gnu.org. 2016. Retrieved .
28. ^ "Perl Regular Expression Documentation". perldoc.perl.org. Retrieved 2012.
29. ^ a b "Regular Expression Syntax". Python 3.5.0 documentation. Python Software Foundation. Retrieved 2015.
30. ^ a b "Essential classes: Regular Expressions: Quantifiers: Differences Among Greedy, Reluctant, and Possessive Quantifiers". The Java Tutorials. Oracle. Retrieved 2016.
31. ^ Cezar Câmpeanu and Kai Salomaa, and Sheng Yu (Dec 2003). "A Formal Study of Practical Regular Expressions". International Journal of Foundations of Computer Science. 14 (6): 1007-1018. Theorem 3 (p.9)
32. ^ Cox (2007)
33. ^ Laurikari (2009)
34. ^ "Vim documentation: pattern". Vimdoc.sourceforge.net. Retrieved .
35. ^ a b
36. ^
37. ^ The character 'm' is not always required to specify a Perl match operation. For example, m/[^abc]/ could also be rendered as /[^abc]/`. The 'm' is only necessary if the user wishes to specify a match operation without using a forward-slash as the regex delimiter. Sometimes it is useful to specify an alternate regex delimiter in order to avoid "delimiter collision". See 'perldoc perlre' for more details.
38. ^ E.g., see Java in a Nutshell, p. 213; Python Scripting for Computational Science, p. 320; Programming PHP, p. 106.
39. ^ Note that all the if statements return a TRUE value
40. ^ Conway, Damian (2005). "Regular Expressions, End of String". Perl Best Practices. O'Reilly. p. 240. ISBN 978-0-596-00173-5.

## References

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over \$50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.