SUPPORT THE WORK

GetWiki

regular expression

ARTICLE SUBJECTS
aesthetics  →
being  →
complexity  →
database  →
enterprise  →
ethics  →
fiction  →
history  →
internet  →
knowledge  →
language  →
licensing  →
linux  →
logic  →
method  →
news  →
perception  →
philosophy  →
policy  →
purpose  →
religion  →
science  →
sociology  →
software  →
truth  →
unix  →
wiki  →
ARTICLE TYPES
essay  →
feed  →
help  →
system  →
wiki  →
ARTICLE ORIGINS
critical  →
discussion  →
forked  →
imported  →
original  →
regular expression
[ temporary import ]
please note:
- the content below is remote from Wikipedia
- it has been imported raw for GetWiki
{{Short description|Sequence of characters that forms a search pattern}}{{Redirect|Regex|the comic book|Re:Gex{{!}}Re:Gex}}{{Redirect|.*|the C++ operator|Pointer (computer science)#Pointer-to-member}}(File:Antony08.gif|thumb|upright=1.5|{{legend|#b0d0f0|outline=#b0d0f0|text=Blue|highlights show the match results of the regular expression pattern: /r[aeiou]+/g (lower case r followed by one or more lower-case vowels).}})A regular expression (shortened as regex or regexp),WEB,weblink Regular Expression Tutorial - Learn How to Use Regular Expressions, Jan, Goyvaerts, Regular-Expressions.info, 2016-10-31, 2016-11-01,weblink" title="web.archive.org/web/20161101212501weblink">weblink sometimes referred to as rational expression,BOOK, Ruslan, Mitkov, The Oxford Handbook of Computational Linguistics,weblink 2003, Oxford University Press, 978-0-19-927634-9, 754, 2016-07-25, 2017-02-28,weblink live, BOOK, Mark V., Lawson, Finite Automata,weblink 17 September 2003, CRC Press, 978-1-58488-255-8, 98–100, 25 July 2016, 27 February 2017,weblink live, is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. Regular expression techniques are developed in theoretical computer science and formal language theory.The concept of regular expressions began in the 1950s, when the American mathematician Stephen Cole Kleene formalized the concept of a regular language. They came into common use with Unix text-processing utilities. Different syntaxes for writing regular expressions have existed since the 1980s, one being the POSIX standard and another, widely used, being the Perl syntax.Regular expressions are used in search engines, in search and replace dialogs of word processors and text editors, in text processing utilities such as sed and AWK, and in lexical analysis. Regular expressions are supported in many programming languages. Library implementations are often called an "engine",WEB, How a Regex Engine Works Internally,weblink regular-expressions.info, 24 February 2024, WEB, How Do You Actually Use Regex?,weblink howtogeek.com, 24 February 2024, and many of these are available for reuse.

History

File:Kleene.jpg|thumb|upright|Stephen Cole KleeneStephen Cole KleeneRegular expressions originated in 1951, when mathematician Stephen Cole Kleene described regular languages using his mathematical notation called regular events.{{sfn|Kleene|1951}}WEB,weblink Regular Languages and Finite Automata, 13 August 2019, Hing, Leung, 16 September 2010, New Mexico State University, The concept of regular events was introduced by Kleene via the definition of regular expressions.,weblink 5 December 2013, dmy-all, These arose in theoretical computer science, in the subfields of automata theory (models of computation) and the description and classification of formal languages. Other early implementations of pattern matching include the SNOBOL language, which did not use regular expressions, but instead its own pattern matching constructs.Regular expressions entered popular use from 1968 in two uses: pattern matching in a text editor{{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 as a means to match patterns in text files.{{sfn|Thompson|1968}}BOOK, Kernighan, Brian, Brian Kernighan, Beautiful Code, A Regular Expressions Matcher, O'Reilly Media, 1–2,weblink 2013-05-15, 978-0-596-51004-6, 2007-08-08, 2020-10-07,weblink live, WEB,weblink An incomplete history of the QED Text Editor, Ritchie, Dennis M., 9 October 2013,weblink" title="web.archive.org/web/19990221023422weblink">weblink 1999-02-21, {{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|p=98}} He later added this capability to the Unix 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: g/re/p meaning "Global search for Regular Expression and Print matching lines").WEB,weblink Jargon File 4.4.7: grep, Eric S. Raymond, Raymond, Eric S. citing Dennis Ritchie, 2003, 2009-02-17, 2011-06-05,weblink" title="web.archive.org/web/20110605165512weblink">weblink 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, sed, AWK, and expr, and in other programs such as Emacs (which has its own, incompatible syntax and behavior). Regexes were subsequently adopted by a wide range of programs, with these early forms standardized in the POSIX.2 standard in 1992.In the 1980s, the more complicated regexes arose in Perl, which originally derived from a regex library written by Henry Spencer (1986), who later wrote an implementation for Tcl called Advanced Regular Expressions.WEB,weblink New Regular Expression Features in Tcl 8.1, 2013-10-11, 2020-10-07,weblink" title="web.archive.org/web/20201007183137weblink">weblink live, The Tcl library is a hybrid NFA/DFA implementation with improved performance characteristics. Software projects that have adopted Spencer's Tcl regular expression implementation include PostgreSQL.WEB,weblink PostgreSQL, Documentation: 9.3: Pattern Matching, 2013-10-12, 2020-10-07,weblink live, Perl later expanded on Spencer's original library to add many new features.WEB,weblink Perl Regular Expressions, perlre, Larry Wall, Wall, Larry, 2006, 2006-10-10, 2009-12-31,weblink" title="web.archive.org/web/20091231010052weblink">weblink live, Part of the effort in the design of Raku (formerly named Perl 6) is to improve Perl's regex integration, and to increase their scope and capabilities to allow the definition of parsing expression grammars.{{harvtxt|Wall|2002}} The result is a mini-language called Raku rules, which are used to define Raku grammar as well as provide a tool to programmers in the language. These rules maintain existing features of Perl 5.x regexes, but also allow BNF-style definition of a recursive descent parser via sub-rules.The use of regexes in structured information standards for document and database modeling started in the 1960s and expanded in the 1980s when industry standards like ISO SGML (precursored by ANSI "GCA 101-1983") consolidated. The kernel of the structure specification language standards consists of regexes. Its use is evident in the DTD element group syntax. Prior to the use of regular expressions, many search languages allowed simple wildcards, for example "*" to match any sequence of characters, and "?" to match a single character. Relics of this can be found today in the glob syntax for filenames, and in the SQL LIKE operator.Starting in 1997, Philip Hazel developed PCRE (Perl Compatible Regular Expressions), which attempts to closely mimic Perl's regex functionality and is used by many modern tools including PHP and Apache HTTP Server.WEB, PCRE - Perl Compatible Regular Expressions,weblink 2024-04-07, www.pcre.org, Today, regexes are widely supported in programming languages, text processing programs (particularly lexers), advanced text editors, and some other programs. Regex support is part of the standard library of many programming languages, including Java and Python, and is built into the syntax of others, including Perl and ECMAScript. In the late 2010s, several companies started to offer hardware, FPGA,WEB,weblink GRegex – Faster Analytics for Unstructured Text Data, grovf.com, 2019-10-22, 2020-10-07,weblink live, GPUWEB,weblink CUDA grep, bkase.github.io, 2019-10-22, 2020-10-07,weblink" title="web.archive.org/web/20201007183138weblink">weblink live, implementations of PCRE compatible regex engines that are faster compared to CPU implementations.

Patterns

The phrase regular expressions, or regexes, is often used to mean the specific, standard textual syntax for representing patterns for matching text, as distinct from the mathematical notation described below. Each character in a regular expression (that is, each character in the string describing its pattern) is either a metacharacter, having a special meaning, or a regular character that has a literal meaning. For example, in the regex b., 'b' is a literal character that matches just 'b', while '.' is a metacharacter that matches every character except a newline. Therefore, this regex matches, for example, 'b%', or 'bx', or 'b5'. Together, metacharacters and literal characters can be used to identify text of a given pattern or process a number of instances of it. Pattern matches may vary from a precise equality to a very general similarity, as controlled by the metacharacters. For example, . is a very general pattern, [a-z] (match all lower case letters from 'a' to 'z') is less general and b is a precise pattern (matches just 'b'). The metacharacter syntax is designed specifically to represent prescribed targets in a concise and flexible way to direct the automation of text processing of a variety of input data, in a form easy to type using a standard ASCII keyboard.A very simple case of a regular expression in this syntax is to locate a word spelled two different ways in a text editor, the regular expression seriali[sz]e matches both "serialise" and "serialize". Wildcard characters also achieve this, but are more limited in what they can pattern, as they have fewer metacharacters and a simple language-base.The usual context of wildcard characters is in globbing similar names in a list of files, whereas regexes are usually employed in applications that pattern-match text strings in general. For example, the regex ^[ t]+|[ t]+$ matches excess whitespace at the beginning or end of a line. An advanced regular expression that matches any numeral is [+-]?(d+(.d*)?|.d+)([eE][+-]?d+)?.File:Thompson-kleene-star.svg|right|thumb|Translating the Kleene starKleene starA regex processor translates a regular expression in the above syntax into an internal representation that can be executed and matched against a string representing the text being searched in. One possible approach is the Thompson's construction algorithm to construct a nondeterministic finite automaton (NFA), which is then made deterministic and the resulting deterministic finite automaton (DFA) is run on the target text string to recognize substrings that match the regular expression.The picture shows the NFA scheme N(s*) obtained from the regular expression s*, where s denotes a simpler regular expression in turn, which has already been recursively translated to the NFA N(s).

Basic concepts

A regular expression, often called a pattern, specifies a set of strings required for a particular purpose. A simple way to specify a finite set of strings is to list its elements or members. However, there are often more concise ways: for example, the set containing the three strings "Handel", "Händel", and "Haendel" can be specified by the pattern H(ä|ae?)ndel; we say that this pattern matches each of the three strings. However, there can be many ways to write a regular expression for the same set of strings: for example, (Hän|Han|Haen)del also specifies the same set of three strings in this example.Most formalisms provide the following operations to construct regular expressions.
Boolean "or" :
A vertical bar separates alternatives. For example, {{code|lang=perl|code=gray{{!}}grey}} can match "gray" or "grey".
Grouping
Parentheses are used to define the scope and precedence of the operators (among other uses). For example, gray|grey and {{code|lang=perl|code=gr(a{{!}}e)y}} are equivalent patterns which both describe the set of "gray" or "grey".
Quantification
A quantifier after an element (such as a token, character, or group) specifies how many times the preceding element is allowed to repeat. The most common quantifiers are the question mark ?, the asterisk * (derived from the Kleene star), and the plus sign + (Kleene plus). {|
?|The question mark indicates zero or one occurrences of the preceding element. For example, colou?r matches both "color" and "colour".
*|The asterisk indicates zero or more occurrences of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.
+|The plus sign indicates one or more occurrences of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".
{n}KERRISK TITLE=GREP(1) - LINUX MANUAL PAGE WEBSITE=MAN7.ORG, 31 January 2023, | The preceding item is matched exactly n times.
|{min,}| The preceding item is matched min or more times.
|{,max}| The preceding item is matched up to max times.
|{min,max}| The preceding item is matched at least min times, but not more than max times.
Wildcard :
The wildcard . matches any character. For example,
a.b matches any string that contains an "a", and then any character and then "b". a.*b matches any string that contains an "a", and then the character "b" at some later point.
These constructions can be combined to form arbitrarily complex expressions, much like one can construct arithmetical expressions from numbers and the operations +, −, ×, and ÷.The precise syntax for regular expressions varies among tools and with context; more detail is given in {{slink||Syntax}}.

Formal language theory

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

Formal definition

Regular expressions consist of constants, which denote sets of strings, and operator symbols, which denote operations over these sets. The following definition is standard, and found as such in most textbooks on formal language theory.{{harvtxt|Hopcroft|Motwani|Ullman|2000}}{{harvtxt|Sipser|1998}} Given a finite alphabet Σ, the following constants are definedas regular expressions:
  • (empty set) ∅ denoting the set ∅.
  • (empty string) ε denoting the set containing only the "empty" string, which has no characters at all.
  • (literal character) a in Σ denoting the set containing only the character a.
Given regular expressions R and S, the following operations over them are definedto produce regular expressions:
  • (concatenation) (RS) denotes the set of strings that can be obtained by concatenating a string accepted by R and a string accepted by S (in that order). For example, let R denote {"ab", "c"} and S denote {"d", "ef"}. Then, (RS) denotes {"abd", "abef", "cd", "cef"}.
  • (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 superset of the set described by R that contains ε and is closed under string concatenation. This is the set of all strings that can be made by concatenating any finite number (including zero) of strings from the set described by R. For example, if R denotes {"0", "1"}, (R) denotes the set of all finite binary strings (including the empty string). If R denotes {"ab", "c"}, (R) denotes {ε, "ab", "c", "abab", "abc", "cab", "cc", "ababab", "abcab", ...}.
To avoid parentheses, it is assumed that the Kleene star has the highest priority followed by concatenation, then alternation. If there is no ambiguity, then parentheses may be omitted. For example, (ab)c can be written as abc, and a|(b(c*)) can be written as a|bc*. Many textbooks use the symbols ∪, +, or ∨ for alternation instead of the vertical bar.Examples:
  • a|b denotes {ε, "a", "b", "bb", "bbb", ...}
  • (a|b) 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", ...}
  • ab(c|ε) 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", ...}
  • (0|(1(010)1)) denotes the set of binary numbers that are multiples of 3: { ε, "0", "00", "11", "000", "011", "110", "0000", "0011", "0110", "1001", "1100", "1111", "00000", ... }

Expressive power and compactness

The formal definition of regular expressions is minimal on purpose, and avoids defining ? and +—these can be expressed as follows: a+ = aa*, and a? = (a|ε). Sometimes the complement operator is added, to give a generalized regular expression; here Rc matches all strings over Σ* that do not match R. In principle, the complement operator is redundant, because it does not grant any more expressive power. However, it can make a regular expression much more concise—eliminating a single complement operator can cause a double exponential blow-up of its length.{{harvtxt|Gelade|Neven|2008|p=332|loc=Thm.4.1}}{{harvtxt|Gruber|Holzer|2008}}Based on {{harvtxt|Gelade|Neven|2008}}, a regular expression of length about 850 such that its complement has a length about 232 can be found at (:File:RegexComplementBlowup.png).Regular expressions in this sense can express the regular languages, exactly the class of languages accepted by deterministic finite automata. There is, however, a significant difference in compactness. Some classes of regular languages can only be described by deterministic finite automata whose size grows exponentially in the size of the shortest equivalent regular expressions. The standard example here is the languagesLk consisting of all strings over the alphabet {a,b} whose kth-from-last letter equals a. On the one hand, a regular expression describing L4 is given by(amid b)^*a(amid b)(amid b)(amid b).Generalizing this pattern to Lk gives the expression:
(amid b)^*aunderbrace{(amid b)(amid b)cdots(amid b)}_{k-1text{ times}}. ,
On the other hand, it is known that every deterministic finite automaton accepting the language Lk must have at least 2k states. Luckily, there is a simple mapping from regular expressions to the more general nondeterministic finite automata (NFAs) that does not lead to such a blowup in size; for this reason NFAs are often used as alternative representations of regular languages. NFAs are a simple variation of the type-3 grammars of the Chomsky hierarchy.In the opposite direction, there are many languages easily described by a DFA that are not easily described by a regular expression. For instance, determining the validity of a given ISBN requires computing the modulus of the integer base 11, and can be easily implemented with an 11-state DFA. However, converting it to a regular expression results in a 2,14 megabytes file .WEB, Regular expressions for deciding divisibility,weblink 2024-02-21, s3.boskent.com, Given a regular expression, Thompson's construction algorithm computes an equivalent nondeterministic finite automaton. A conversion in the opposite direction is achieved by Kleene's algorithm.Finally, it is worth noting that many real-world "regular expression" engines implement features that cannot be described by the regular expressions in the sense of formal language theory; rather, they implement regexes. See below for more on this.

Deciding equivalence of regular expressions

As seen in many of the examples above, there is more than one way to construct a regular expression to achieve the same results.It is possible to write an algorithm that, for two given regular expressions, decides whether the described languages are equal; the algorithm reduces each expression to a minimal deterministic finite state machine, and determines whether they are isomorphic (equivalent).Algebraic laws for regular expressions can be obtained using a method by Gischer which is best explained along an example: In order to check whether (X+Y)* and (X* Y*)* denote the same regular language, for all regular expressions X, Y, it is necessary and sufficient to check whether the particular regular expressions (a+b)* and (a* b*)* denote the same language over the alphabet Σ={a,b}. More generally, an equation E=F between regular-expression terms with variables holds if, and only if, its instantiation with different variables replaced by different symbol constants holds.REPORT, Jay L., Gischer, Stanford Univ., Dept. of Comp. Sc., (Title unknown), Technical Report, STAN-CS-TR-84-1033, 1984, {{Title missing|date=February 2023}}BOOK, 978-0-201-44124-6, John E., Hopcroft, Rajeev, Motwani, Jeffrey D., Ullman, amp, Introduction to Automata Theory, Languages, and Computation, Upper Saddle River, New Jersey, Addison Wesley, 2003, 117–120, This property need not hold for extended regular expressions, even if they describe no larger class than regular languages; cf. p.121., Every regular expression can be written solely in terms of the Kleene star and set unions over finite words. This is a surprisingly difficult problem. As simple as the regular expressions are, there is no method to systematically rewrite them to some normal form. The lack of axiom in the past led to the star height problem. In 1991, Dexter Kozen axiomatized regular expressions as a Kleene algebra, using equational and Horn clause axioms.{{harvtxt|Kozen|1991}}{{page needed|date=February 2015}}Already in 1964, Redko had proved that no finite set of purely equational axioms can characterize the algebra of regular languages.JOURNAL, V.N., Redko,weblink On defining relations for the algebra of regular events, Ukrainskii Matematicheskii Zhurnal, 1964, 16, 1, 120–126, 2018-03-28, 2018-03-29,weblink" title="web.archive.org/web/20180329121016weblink">weblink live, Russian,

Syntax

A regex pattern matches a target string. The pattern is composed of a sequence of atoms. An atom is a single point within the regex pattern which it tries to match to the target string. The simplest atom is a literal, but grouping parts of the pattern to match an atom will require using ( ) as metacharacters. Metacharacters help form: atoms; quantifiers telling how many atoms (and whether it is a greedy quantifier or not); a logical OR character, which offers a set of alternatives, and a logical NOT character, which negates an atom's existence; and backreferences to refer to previous atoms of a completing pattern of atoms. A match is made, not when all the atoms of the string are matched, but rather when all the pattern atoms in the regex have matched. The idea is to make a small pattern of characters stand for a large number of possible strings, rather than compiling a large list of all the literal possibilities.Depending on the regex processor there are about fourteen metacharacters, characters that may or may not have their literal character meaning, depending on context, or whether they are "escaped", i.e. preceded by an escape sequence, in this case, the backslash . Modern and POSIX extended regexes use metacharacters more often than their literal meaning, so to avoid "backslash-osis" or leaning toothpick syndrome, they have a metacharacter escape to a literal mode; starting out, however, they instead have the four bracketing metacharacters ( ) and { } be primarily literal, and "escape" this usual meaning to become metacharacters. Common standards implement both. The usual metacharacters are {}[]()^$.|*+? and . The usual characters that become metacharacters when escaped are dswDSW and N.

Delimiters

When entering a regex in a programming language, they may be represented as a usual string literal, hence usually quoted; this is common in C, Java, and Python for instance, where the 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.

IEEE POSIX Standard

The IEEE POSIX standard has three sets of compliance: BRE (Basic Regular Expressions),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 ERE (Extended Regular Expressions), and SRE (Simple Regular Expressions). SRE is deprecated,The Single Unix Specification (Version 2) 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. As in POSIX EREs, ( ) and { } are treated as metacharacters unless escaped; other metacharacters are known to be literal or symbolic based on context alone. Additional functionality includes lazy matching, backreferences, named capture groups, and recursive patterns.

POSIX basic and extended

In the POSIX standard, Basic Regular Syntax (BRE) requires that the metacharacters ( ) and { } be designated () and {}, whereas Extended Regular Syntax (ERE) does not.{| class="wikitable"! Metacharacter! Description
valign="top"!^|Matches the starting position within the string. In line-based tools, it matches the starting position of any line.
valign="top"!.|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, a.c matches "abc", etc., but [a.c] matches only "a", ".", or "c".
valign="top"![ ]|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]. Backslash escapes are not allowed. The ] character can be included in a bracket expression if it is the first (after the ^) character: []abc].
valign="top"![^ ]|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.
valign="top"!$|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"!( )
n). A marked subexpression is also called a block or capturing group. BRE mode requires {{nowrap>( )}}.
valign="top"!n
nth marked subexpression matched, where n is a digit from 1 to 9. This construct is defined in the POSIX standard.HTTPS://PUBS.OPENGROUP.ORG/ONLINEPUBS/9699919799/BASEDEFS/V1_CHAP09.HTML#TAG_09_03_06 TITLE=THE OPEN GROUP BASE SPECIFICATIONS ISSUE 7, 2018 EDITION YEAR=2017, December 10, 2023, Some tools allow referencing more than nine capturing groups. Also known as a back-reference, this feature is supported in BRE mode.
valign="top"!*|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.
valign="top"!{{nowrap|{m,n}}}
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 {{nowrap>{m,n}}}.
Examples:
  • .at matches any three-character string ending with "at", including "hat", "cat", "bat", "4at", "at" and " at" (starting with a space).
  • [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]", "[b]", "[7]", "[@]", "[)", and "[ ]" (bracket space bracket).
  • s. matches s followed by zero or more characters, for example: "s", "saw", "seed", "s3w96.7", and "s6h%(>>>m n mQ".
According to Ross Cox, the POSIX specification requires ambiguous subexpressions to be handled in a way different from Perl's. The committee replaced Perl's rules with one that is simple to explain, but the new "simple" rules are actually more complex to implement: they were incompatible with pre-existing tooling and made it essentially impossible to define a "lazy match" (see below) extension. As a result, very few programs actually implement the POSIX subexpression rules (even when they implement other parts of the POSIX syntax).WEB, Regular Expression Matching: the Virtual Machine Approach,weblink Ross Cox, 2009, swtch.com, Digression: POSIX Submatching,

Metacharacters in POSIX extended

The meaning of metacharacters escaped with a backslash is reversed for some characters in the POSIX Extended Regular Expression (ERE) syntax. With this syntax, a backslash causes the metacharacter to be treated as a literal character. So, for example, ( ) is now ( ) and { } is now { }. Additionally, support is removed for n backreferences and the following metacharacters are added:{| class="wikitable"! Metacharacter! Description
valign="top"! ?| 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".
! |
def matches "abc" or "def".
Examples:
  • [hc]?at matches "at", "hat", and "cat".
  • [hc]at matches "at", "hat", "cat", "hhat", "chat", "hcat", "cchchat", 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 any uppercase letter in the English alphabet, and d could mean any digit. Character classes apply to both POSIX levels.When specifying a range of characters, such as [a-Z] (i.e. lowercase a to uppercase Z), the computer's locale settings determine the contents by the numeric ordering of the character encoding. They could store digits in that sequence, or the ordering could be abc...zABC...Z, or aAbBcC...zZ. So the POSIX standard defines a character class, which will be known by the regex processor installed. Those definitions are in the following table:{| class="wikitable sortable"! Description! POSIX !! Perl/Tcl !! Vim !! Java !! ASCII
| ASCII characters|||| p{ASCII}| [x00-x7F]
| Alphanumeric characters| [:alnum:]||| p{Alnum}| [A-Za-z0-9]
| Alphanumeric characters plus "_"|| w| w| w| [A-Za-z0-9_]
| Non-word characters|| W| W| W| [^A-Za-z0-9_]
| Alphabetic characters| [:alpha:]|| a| p{Alpha}| [A-Za-z]
| Space and tab| [:blank:]|| s| p{Blank}| [ t]
| Word boundaries|| b| < >| b| (?

- content above as imported from Wikipedia
- "regular expression" does not exist on GetWiki (yet)
- time: 2:41pm EDT - Wed, May 15 2024
[ this remote article is provided by Wikipedia ]
LATEST EDITS [ see all ]
GETWIKI 23 MAY 2022
GETWIKI 09 JUL 2019
Eastern Philosophy
History of Philosophy
GETWIKI 09 MAY 2016
GETWIKI 18 OCT 2015
M.R.M. Parrott
Biographies
GETWIKI 20 AUG 2014
CONNECT