{
  "id": "regular-language",
  "title": "Regular Language",
  "lang": "en",
  "source_lang": "en",
  "summary": "A regular language is a set of finite strings recognizable by a finite automaton, equivalently describable by a classical regular expression.",
  "category": "computer-science",
  "subcategory": "algorithms-theory",
  "type": "concept",
  "aliases": [
    "Recognizable language",
    "Finite-state language",
    "Regular set"
  ],
  "generated_at": "2026-11-03",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/regular-language/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/regular-language/",
      "json": "https://aiwiki.page/zh/regular-language.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "A regular language is a set of finite strings whose membership can be determined by a machine with finitely many states. Equivalently, it is a language describable by a classical regular expression or generated by a suitable finite grammar. These equivalent descriptions connect patterns written as expressions with machines that recognize them and algebraic structures that explain their properties.\n\nRegular languages are fundamental to computer science because they combine expressive usefulness with strong mathematical and algorithmic guarantees. They describe many lexical patterns, communication constraints, and finite-state behaviors, while supporting effective operations such as intersection, complementation, and equivalence testing. Their central limitation is equally important: a fixed finite-state device cannot retain an unbounded amount of information about an input.\n\nThe theory brings together automata, grammars, algebra, and logic. It explains both why a pattern such as “binary strings ending in 01” is regular and why patterns requiring arbitrary matching counts or nesting generally are not. It also distinguishes the mathematical meaning of “regular expression” from programming-library features that can recognize languages beyond the regular class."
    },
    {
      "heading": "Mathematical definition and basic examples",
      "text": "The starting point is a finite alphabet \\(\\Sigma\\), whose elements are called symbols. A string, or word, is a finite sequence of symbols from that alphabet. The empty string is denoted by \\(\\varepsilon\\), and the set of all finite strings over \\(\\Sigma\\) is denoted by \\(\\Sigma^*\\). A formal language over \\(\\Sigma\\) is any subset \\(L\\subseteq\\Sigma^*\\). Regularity is a property of such a set, not of the typography or natural-language interpretation of its strings.\n\nOne inductive definition begins with the languages \\(\\varnothing\\), \\(\\{\\varepsilon\\}\\), and \\(\\{a\\}\\) for each symbol \\(a\\in\\Sigma\\). Regular languages are exactly those obtainable from these basic languages through finitely many applications of union, concatenation, and Kleene star. Union combines alternatives. Concatenation combines strings in sequence:\n\n\\[LK=\\{uv:u\\in L,\\ v\\in K\\}.\\]\n\nKleene star allows any finite number of repetitions:\n\n\\[L^*=\\bigcup_{n\\geq 0}L^n, \\qquad L^0=\\{\\varepsilon\\}.\\]\n\nThe zero-repetition case is essential: every starred language contains the empty string.\n\nOver the alphabet \\(\\{0,1\\}\\), the language of strings ending in \\(01\\) is regular and is denoted by \\((0\\mid1)^*01\\). The language containing an even number of \\(1\\) symbols is also regular. A recognizer needs only to remember whether the count so far is even or odd, not its exact value. More generally, divisibility conditions on symbol counts can be recognized by storing remainders modulo a fixed positive integer. For binary numerals read from left to right, divisibility by \\(m\\) can be tracked using the update \\(r\\mapsto(2r+b)\\bmod m\\), where \\(b\\) is the next bit.\n\nEvery finite language is regular, because it can be expressed as a finite union of individual words. Infinite regular languages include \\(\\Sigma^*\\), \\(a^*\\), and the set of all strings containing a particular fixed substring. Neither infinitude nor repetition therefore makes a language nonregular. Conversely, a language can have a short mathematical description and still be nonregular: \\(\\{a^n b^n:n\\geq0\\}\\) requires an equality between two arbitrarily large counts.\n\nThe alphabet is part of the mathematical setting. Complementation means complement relative to a specified \\(\\Sigma^*\\), and changing that alphabet can change the complement. Symbols also need not be printed characters: they may represent tokens, events, instruction classes, or categories of input. What matters in the classical theory is that the alphabet is finite and that each word has finite length."
    },
    {
      "heading": "Recognition by finite automata",
      "text": "A regular language can be recognized by a finite automaton. A deterministic finite automaton, or DFA, is conventionally specified as\n\n\\[A=(Q,\\Sigma,\\delta,q_0,F),\\]\n\nwhere \\(Q\\) is a finite set of states, \\(\\Sigma\\) is the input alphabet, \\(\\delta:Q\\times\\Sigma\\to Q\\) is the transition function, \\(q_0\\) is the initial state, and \\(F\\subseteq Q\\) is the set of accepting states. Reading a symbol changes the current state according to \\(\\delta\\). A word is accepted precisely when the state reached after its last symbol belongs to \\(F\\).\n\nFor example, a DFA recognizing binary strings with an even number of \\(1\\) symbols has two states, “even” and “odd.” It starts in the accepting even state. Reading \\(0\\) leaves the state unchanged; reading \\(1\\) switches states. The machine accepts the empty string because its initial state is accepting. This illustrates the finite-state interpretation of memory: the machine retains only information relevant to future acceptance, not the entire prefix it has read.\n\nA nondeterministic finite automaton, or NFA, permits several possible next states for a state-symbol pair. Some definitions also permit \\(\\varepsilon\\)-transitions, which consume no input. A word is accepted if at least one possible path consumes the whole word and ends in an accepting state. Nondeterminism changes the representation, but not the class of recognizable languages. Every NFA has an equivalent DFA, and every DFA is already a special case of an NFA.\n\nThe standard conversion is the subset construction. Each DFA state represents a set of possible NFA states. After reading a prefix, that set contains exactly the NFA states reachable by reading the prefix, including appropriate closures under \\(\\varepsilon\\)-transitions. If an NFA has \\(n\\) states, its equivalent subset DFA has at most \\(2^n\\) states. Some language families require exponentially many DFA states relative to the size of an NFA, so nondeterminism can provide genuine descriptive compression even though it adds no expressive power.\n\nFinite automata also admit equivalent grammar-based descriptions. A right-linear grammar uses productions such as \\(A\\to aB\\), \\(A\\to a\\), and \\(A\\to\\varepsilon\\). Nonterminals correspond to states, and productions correspond to transitions or termination. Left-linear grammars likewise generate exactly the regular languages. Arbitrarily mixing left-linear and right-linear productions, however, does not preserve this restriction: the directionality requirement is substantive.\n\nThe equivalence of deterministic and nondeterministic recognition was established in the foundational development of automata theory. Michael O. Rabin and Dana Scott’s 1959 paper on finite automata helped consolidate the mathematical treatment of finite-state recognition and its decision problems."
    },
    {
      "heading": "Regular expressions and equivalent descriptions",
      "text": "Classical regular expressions provide a compositional notation for regular languages. Their basic expressions denote the empty language, the empty string, and individual alphabet symbols. The operations are alternation, concatenation, and Kleene star. Parentheses specify grouping; conventional precedence places star above concatenation and concatenation above alternation. Additional operators such as “one or more” and “optional” are conveniences:\n\n\\[R^+=RR^*, \\qquad R?=(\\varepsilon\\mid R).\\]\n\nBounded repetition also adds convenience rather than expressive power when the bounds are fixed finite integers.\n\nKleene’s theorem states that a language is denoted by a classical regular expression if and only if it is recognizable by a finite automaton. Stephen Cole Kleene developed this connection in work on events represented by nerve nets and finite automata, published in 1956. Its significance is constructive: there are algorithms translating expressions into automata and automata into expressions, rather than merely an abstract coincidence between two definitions.\n\nIn an expression-to-automaton construction, each subexpression contributes a small machine fragment. Alternation branches between fragments, concatenation connects them in sequence, and star introduces paths for repetition and for zero occurrences. Ken Thompson’s 1968 regular-expression search algorithm popularized a particularly influential construction using \\(\\varepsilon\\)-transitions. In the other direction, state elimination replaces paths through eliminated states with expressions. If a state has a loop labeled \\(R\\), an incoming label \\(P\\), and an outgoing label \\(Q\\), paths through that state contribute an expression of the form \\(PR^*Q\\).\n\nEquivalence of expressive power does not imply equivalence of size. Translating an automaton into an ordinary expression can produce an exponentially larger representation in the worst case. Eliminating states in different orders can also yield substantially different expressions. Thus the clearest human-readable pattern and the most efficient machine representation need not coincide. Expressions are convenient for composition and editing, whereas automata make many semantic operations and decision procedures more direct.\n\nProgramming-library “regular expressions” require a separate distinction. Character classes, fixed repetitions, and many assertions can be implemented without leaving regular-language recognition. Backreferences, by contrast, may require a later substring to equal an arbitrarily long earlier substring. For instance, under whole-string matching semantics, a captured nonempty word followed by a backreference can describe \\(\\{ww:w\\in\\Sigma^+\\}\\), which is nonregular when the alphabet contains at least two symbols.\n\nMatching policy is another independent issue. Greedy and lazy choices usually affect which match or captured substring is returned rather than the underlying regular-language expressive power of the basic operators. Search, whole-string recognition, and capture extraction are related tasks, but their observable results and computational costs must not be conflated."
    },
    {
      "heading": "Closure properties and language constructions",
      "text": "Regular languages are closed under a broad collection of operations: applying one of these operations to regular inputs produces a regular result. Closure under union, concatenation, and star follows directly from their inductive definition. Automata provide particularly transparent proofs of closure under Boolean operations, including intersection, complement, and difference. These properties allow complex specifications to be assembled from independent constraints.\n\nFor intersection, let two DFAs have state sets \\(Q_1\\) and \\(Q_2\\). Their product automaton uses pairs in \\(Q_1\\times Q_2\\), advancing both components on each input symbol. A pair is accepting when both component states are accepting. Changing that acceptance condition gives union or other Boolean combinations. The product has at most \\(|Q_1||Q_2|\\) states. Complementation is simpler: for a complete DFA, replace its accepting set \\(F\\) by \\(Q\\setminus F\\). Completeness matters because missing transitions must first be directed to a rejecting sink state.\n\nRegular languages are also closed under reversal. Reversing every transition of an automaton and exchanging the roles of initial and final states yields a nondeterministic recognizer for the reversed language, with a new initial state if necessary. They are closed under homomorphism as well. A word homomorphism maps each symbol to a fixed word, possibly empty, and extends by concatenation. Applying it to a regular language preserves regularity because symbol transitions can be replaced by paths spelling the corresponding words.\n\nInverse homomorphism preserves regularity too. If \\(h:\\Gamma^*\\to\\Sigma^*\\) is a homomorphism and \\(L\\subseteq\\Sigma^*\\) is regular, then\n\n\\[h^{-1}(L)=\\{w\\in\\Gamma^*:h(w)\\in L\\}\\]\n\nis regular. A recognizer can process a symbol \\(a\\in\\Gamma\\) by simulating the transitions for the fixed word \\(h(a)\\). This construction is useful when relating encodings, token alphabets, or abstract events to concrete strings.\n\nQuotients provide a stronger and sometimes less intuitive closure property. For languages \\(L\\) and \\(K\\), the right quotient is\n\n\\[L/K=\\{x:\\text{there exists }y\\in K\\text{ with }xy\\in L\\}.\\]\n\nIf \\(L\\) is regular, then \\(L/K\\) is regular even when \\(K\\) is arbitrary. In a DFA for \\(L\\), the accepting states can be replaced by the states from which some word in \\(K\\) reaches an original accepting state. This establishes existence, but does not necessarily supply an effective algorithm when \\(K\\) lacks a usable finite description.\n\nClosure properties support both construction and impossibility proofs. Intersecting a complicated language with a simple regular language can isolate a nonregular core. Conversely, constraints such as a required prefix, forbidden substrings, and parity conditions can be combined mechanically into one finite-state recognizer."
    },
    {
      "heading": "Nonregularity and limits of finite memory",
      "text": "Regular-language theory gives precise ways to show that finite memory is insufficient. The most familiar is the pumping lemma for regular languages. If \\(L\\) is regular, there is a positive integer \\(p\\) such that every \\(w\\in L\\) with \\(|w|\\geq p\\) can be written as \\(w=xyz\\), where\n\n\\[|xy|\\leq p,\\qquad |y|>0, \\qquad xy^iz\\in L\\text{ for every }i\\geq0.\\]\n\nThe repeated segment exists because an accepting computation on a sufficiently long word must revisit a state.\n\nTo prove that \\(L=\\{a^n b^n:n\\geq0\\}\\) is nonregular, suppose a pumping length \\(p\\) exists and choose \\(w=a^p b^p\\). Every permitted decomposition places the nonempty segment \\(y\\) entirely among the initial \\(a\\) symbols. Pumping it out produces fewer \\(a\\) symbols than \\(b\\) symbols, so \\(xz\\notin L\\), contradicting the lemma. The proof must cover every decomposition satisfying the stated restrictions; choosing one convenient decomposition is not enough.\n\nThe lemma is a necessary condition for regularity, not a sufficient characterization. Some nonregular languages satisfy its pumping condition. It therefore cannot establish regularity simply because a proposed pumping argument succeeds or because attempts to find a contradiction fail. Direct automaton construction, a regular expression, or a full characterization theorem is needed for that purpose.\n\nThe Myhill–Nerode theorem gives such a characterization. For a language \\(L\\), define\n\n\\[x\\equiv_L y \\quad\\Longleftrightarrow\\quad \\forall z\\in\\Sigma^*,\\ (xz\\in L\\iff yz\\in L).\\]\n\nTwo prefixes are equivalent exactly when no continuation distinguishes their membership behavior. The theorem states that \\(L\\) is regular if and only if this relation has finitely many equivalence classes. Each class represents one distinct kind of information about the past that a recognizer must retain.\n\nFor \\(\\{a^n b^n:n\\geq0\\}\\), the prefixes \\(a^0,a^1,a^2,\\ldots\\) are pairwise distinguishable: appending \\(b^i\\) accepts \\(a^i\\) but not \\(a^j\\) for \\(j\\neq i\\). Infinitely many distinguishable prefixes require infinitely many states. Similar reasoning proves the nonregularity of unrestricted balanced parentheses and palindromes over a sufficiently rich alphabet.\n\nThis boundary is about unbounded requirements. Balanced parentheses with a fixed maximum nesting depth form a regular language, as do equal-count patterns restricted to a fixed maximum input length. Unrestricted nesting is naturally handled by a pushdown automaton, whose stack supports the broader class of context-free languages. Finite bounds can turn an otherwise nonregular specification into a finite-state one, sometimes at considerable state cost."
    },
    {
      "heading": "Minimal automata and effective decision procedures",
      "text": "Every regular language has a minimal complete DFA, unique up to renaming of states. Its states correspond to the Myhill–Nerode equivalence classes, its initial state is the class of \\(\\varepsilon\\), and reading a symbol \\(a\\) sends the class of \\(x\\) to the class of \\(xa\\). Accepting classes are those containing words of the language. Minimality therefore has a semantic meaning: two distinct states must differ on the acceptance of some future suffix.\n\nDFA minimization is commonly performed by partition refinement. Unreachable states are removed first. The remaining states are initially partitioned into accepting and nonaccepting groups. A group is then split whenever two of its states have transitions, on some symbol, into different groups. Refinement continues until every group is stable under all transitions. States in the same final group have identical future behavior and can be merged.\n\nJohn Hopcroft’s minimization algorithm, introduced in 1971, organizes these refinements to achieve \\(O(|\\Sigma|n\\log n)\\) time under standard explicit-transition assumptions, where \\(n\\) is the number of states. This is substantially better than repeatedly comparing every pair in large automata. Practical performance also depends on whether transitions are stored densely or sparsely and whether alphabet symbols are represented individually or grouped into classes.\n\nMany semantic questions become graph problems. A DFA or NFA accepts at least one word exactly when an accepting state is reachable from an initial state. Its language is infinite exactly when there is a directed cycle that is reachable from an initial state and from which acceptance can still be reached, with the usual symbol-consuming transition representation. For \\(\\varepsilon\\)-NFAs, a cycle consisting only of empty transitions does not itself establish infinitude.\n\nEquivalence of two DFAs can be checked by exploring their product and looking for a reachable pair in which exactly one component is accepting. Such a pair witnesses a word in their symmetric difference. A breadth-first search can recover a shortest distinguishing word. Inclusion \\(L_1\\subseteq L_2\\) is similarly reduced to emptiness of \\(L_1\\cap\\overline{L_2}\\). These procedures are valuable in testing whether two independently constructed recognizers implement the same specification.\n\nThe representation determines computational complexity. DFA equivalence is efficiently decidable, while equivalence and universality for explicitly represented NFAs are PSPACE-complete when automaton size is the input measure. The difference reflects the compactness of nondeterministic representation, not a difference in recognized language classes. Likewise, an operation that is simple on a DFA may become expensive when its input is a compact expression whose equivalent deterministic automaton is exponentially larger."
    },
    {
      "heading": "Algebraic and logical characterizations",
      "text": "Finite automata have an algebraic interpretation through monoids, associative structures with an identity element. Words under concatenation form the free monoid \\(\\Sigma^*\\), with identity \\(\\varepsilon\\). A language \\(L\\) is regular exactly when there are a finite monoid \\(M\\), a homomorphism \\(h:\\Sigma^*\\to M\\), and a subset \\(P\\subseteq M\\) such that\n\n\\[L=h^{-1}(P).\\]\n\nThe finite monoid records enough information about a word to determine membership, while respecting concatenation.\n\nAn automaton supplies such a monoid because each word induces a transformation of its state set. Reading \\(uv\\) composes the transformation for \\(u\\) with that for \\(v\\). Since the state set is finite, only finitely many transformations are possible. This formulation shifts attention from individual runs to how entire words act on all possible states, making concatenation behavior directly accessible.\n\nThe canonical algebraic object is the syntactic monoid. Define\n\n\\[u\\sim_L v \\quad\\Longleftrightarrow\\quad \\forall x,y\\in\\Sigma^*,\\ (xuy\\in L\\iff xvy\\in L).\\]\n\nUnlike Myhill–Nerode equivalence, which tests continuations on the right, syntactic equivalence tests contexts on both sides. Its quotient is a monoid, and \\(L\\) is regular exactly when that monoid is finite. For regular languages, it is isomorphic to the transition monoid of the minimal DFA.\n\nRegular languages also admit a logical characterization. A finite word can be viewed as a finite ordered set of positions, equipped with unary predicates stating which symbol occupies each position. Monadic second-order logic permits quantification over positions and over sets of positions. The Büchi–Elgot–Trakhtenbrot theorem characterizes regular languages as exactly those definable in this logic over finite words. Automaton runs can be encoded by sets recording the positions associated with each state.\n\nRestricting the logic reveals meaningful subclasses. First-order logic with the linear order of positions defines exactly the star-free languages: languages describable using union, concatenation, and complement, without Kleene star. Schützenberger’s algebraic characterization identifies these with languages whose finite syntactic monoids are aperiodic. Here aperiodic means that for every monoid element \\(s\\), some power satisfies \\(s^n=s^{n+1}\\).\n\nA parity condition illustrates the distinction. “The number of \\(a\\) symbols is even” is regular, but is not definable in first-order logic using only order and letter predicates. Its recognition depends on a persistent two-cycle. Thus finite-state recognition encompasses both purely order-based constraints and modular counting behavior; algebra and logic distinguish these forms even when both have small automata."
    },
    {
      "heading": "Recognition algorithms and practical matching costs",
      "text": "Once a DFA has been constructed, whole-word recognition is straightforward. Starting at the initial state, the recognizer performs one transition per input symbol and checks acceptance after the final symbol. For an input of length \\(n\\), this takes \\(O(n)\\) time with constant-time transition lookup. Relative to a fixed automaton, the working memory for recognition is constant: only the current state and basic input-processing information are needed. The stored automaton is a separate representation cost.\n\nNFA simulation avoids constructing the full subset DFA in advance. The simulator maintains the currently reachable set of states and updates it for each symbol. For a Thompson-style NFA of size \\(m\\), conventional simulation takes \\(O(mn)\\) time and \\(O(m)\\) working space, subject to the implementation of empty-transition closure. This is linear in input length for a fixed pattern. Lazy determinization occupies a middle ground by creating subset states only as encountered and potentially caching them.\n\nBacktracking matchers follow a different execution strategy. They explore alternative paths and retreat when a choice fails. Even a classical regular pattern can cause exponentially many explored paths on some inputs if the implementation repeatedly revisits equivalent situations. For example, nested repetitions such as (a+)+ under whole-string matching may produce extensive backtracking on a long run of a characters followed by a nonmatching character. The language is regular; the high cost comes from the recognition strategy.\n\nSuch behavior underlies regular-expression denial of service, a form of denial-of-service attack in which crafted inputs consume excessive matching time. Automata-based execution can avoid this particular source of exponential path exploration for regular constructs. It does not eliminate every possible resource problem: pattern compilation, determinization, capture processing, and large transition tables may have substantial costs of their own.\n\nText representation adds another layer. The theoretical alphabet might consist of bytes, Unicode scalar values, or application-defined tokens. A byte-oriented automaton and a code-point-oriented automaton recognize languages over different alphabets, even when they are intended to describe the same visible text. Unicode normalization, case folding, and grapheme segmentation are separate transformations or interpretation rules rather than automatic consequences of regular-language theory.\n\nRecognition must also be distinguished from finding a match inside a larger input and selecting among competing matches. Leftmost-first and leftmost-longest semantics can return different substrings or captures. POSIX matching rules and common backtracking-library conventions therefore specify more than a set of accepted whole strings. Complexity claims need to identify the task, the pattern representation, and whether preprocessing costs are included."
    },
    {
      "heading": "Applications and relationships with other language classes",
      "text": "A major application is lexical analysis in a compiler. A lexer classifies input segments as identifiers, keywords, numerals, operators, and other token categories. Many token classes are regular: an identifier might begin with a letter and continue with letters or digits, while a numeral follows a finite pattern of signs, digits, decimal points, and exponents. Lexer generators combine token expressions into a recognizer, commonly using longest-match rules and priority rules to resolve overlaps.\n\nLexical recognition is not the same as recognizing the syntax of a complete programming language. Arbitrarily nested expressions, blocks, and matched delimiters generally require mechanisms beyond finite automata. Parsers commonly use context-free methods, while semantic constraints such as declaration-before-use or type consistency require additional structures. The separation between lexing, parsing, and semantic analysis reflects different computational requirements, although practical language tools may blur these boundaries.\n\nIn formal verification, finite automata describe allowed event sequences and finite-state components. Intersections combine a system model with a monitor for a prohibited behavior; reachability can then reveal a violating execution. Regular safety constraints include forbidding a particular event before authentication or requiring an acknowledgment before another request. A protocol with bounded queues can have a finite-state model, whereas unbounded queues or arbitrarily many participants may require stronger models or abstractions.\n\nRegular languages also support path queries in a database or labeled graph. A regular path query specifies an allowed sequence of edge labels, such as zero or more “parent” edges followed by one “sibling” edge. Evaluation can use a product of graph vertices and automaton states. Reachability in that product identifies endpoints connected by a matching path. The regular expression constrains label sequences; additional requirements, such as restricting paths to be simple, can alter the problem substantially.\n\nFinite-state methods extend beyond accept-or-reject recognition. Finite-state transducers associate inputs with outputs and are used in morphological analysis, text normalization, and speech recognition. Weighted automata attach numerical values to transitions or paths, enabling scoring and probabilistic interpretations. These systems build on finite-state structure but require additional definitions: a weighted computation is not merely membership in an ordinary language.\n\nWithin the Chomsky hierarchy, regular languages form the class generated by type-3 grammars. They are properly contained in the context-free languages and, through the broader hierarchy, in the languages recognizable by a Turing machine. Extensions also change the objects being recognized: finite tree automata process branching structures, while Büchi automata recognize languages of infinite words. Their acceptance conditions and closure properties require separate treatment; acceptance after a final input symbol has no direct counterpart when the input never ends."
    }
  ],
  "links": [
    "computer-science",
    "formal-language",
    "finite-state-machine",
    "pumping-lemma",
    "breadth-first-search",
    "computational-complexity",
    "denial-of-service-attack",
    "unicode",
    "posix",
    "compiler",
    "programming-language",
    "formal-verification",
    "database",
    "speech-recognition",
    "turing-machine"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}