TL;DR
A formal language is a set of strings, and a regular expression is a short written pattern that names exactly one such set. Its building blocks are single symbols, joining, choosing between options, and repeating. A state machine can decide, reading a string one symbol at a time, whether the string matches the pattern. That is why search tools, text editors and the first stage of a compiler can all use the same notation.
Builds on: Formal Language, State Machine · Leads to: Lexical Analysis, Context-Free Grammar
Where it's used
Search and find-and-replace. Editors and the Unix tool grep let you type a pattern such as colou?r and find every matching word. The user writes a few symbols, and the tool searches a whole file for the set of strings those symbols describe.
Input checking. A web form that asks for a postcode, a username or a product code often checks the input against a pattern before accepting it. The pattern states the allowed shape exactly, so a typo is rejected at once instead of breaking later steps.
Compilers and tokenisers. A programming language's keywords, numbers and identifiers are each described by a pattern. A lexer matches these patterns to turn the source code into a stream of tokens. Each pattern is compiled into a state machine, so the scan takes one pass over the text.
How it works
We follow the pattern ab*, which means one a followed by any number of bs, including none. It matches a, ab, abb and so on. We check whether the string abb matches.
Build a state machine for the pattern first. It has three states: q0 (start), q1 (just read an a), and a dead state for anything that cannot match. q1 is accepting, which means a string that ends there matches.
- Start in
q0. Nothing has been read yet. Check: a machine with no input has not yet matched anything. - Read the first symbol,
a. The rule forq0onamoves toq1. Check: the pattern starts witha, so readingaat the start is the only valid first move. - Read the second symbol,
b. The rule forq1onbstays inq1, because theb*part can repeat. Check:abis in the set, so the machine should still be in a state that can continue. - Read the third symbol,
b. The rule forq1onbstays inq1. Check:abbis also in the set, and the machine is still in the accepting state. - The string has ended in
q1, which is accepting. Soabbmatches. Check: if the string had ended inq0, it would not match, becauseab*needs at least onea.
The diagram shows the machine. An arrow labelled with a symbol is the rule for reading that symbol. The arrow to the end marker [*] marks q1 as the accepting state. The dead state is left out of the diagram to keep it short.
stateDiagram-v2 [*] --> q0 q0 --> q1 : a q1 --> q1 : b q1 --> [*]
For the string ba, the machine starts in q0, reads b, has no rule for that, and goes to the dead state. The string does not match, as the pattern requires an a first.
The math
A regular expression is built over an alphabet (the set of allowed symbols) from these pieces: a symbol , the empty string , concatenation , choice , and repetition . Each expression names a language , a set of strings.
for each symbol ; ; ; ; , where means strings from joined one after another.
Step 1 in symbols: the symbols
The pattern is the concatenation of and . The language of is , and of is .
Step 2 in symbols: repetition
The star gives , because , , , and so on. Here is the empty string, and gives the option of no at all.
Step 3 in symbols: concatenation
Joining with gives
The string is in this set because , with and .
Step 4 in symbols: the machine agrees
The state machine accepts exactly the strings in . This is the connection the whole idea rests on: a pattern names a set, and a finite machine recognises that same set. Stephen Kleene proved in 1956 that the two descriptions match for every regular expression.
Worked examples
Let the pattern be . Decide whether each of , and is in .
- The string must begin with , because every string in starts with . It starts with , so is not in the set.
- The string is followed by three s. That is with , so it is in the set.
- The string is followed by another . The part after the first must be all s, but it is , so is not in the set.
Of the three, only matches.
Let the pattern be , where the question mark means the is optional. The pattern names exactly two strings, : the is either present or absent.
- Read the pattern from left to right. It requires the letters c, o, l, o, then an optional u, then r.
- Test "color". Read c, o, l, o, skip the optional u because the next letter is r, then read r. The string ends in an accepting state, so it matches.
- Test "colour". Read c, o, l, o, then u (the optional letter, taken this time), then r. It matches too.
- Test "colr". After c, o, l, the pattern needs another o. The next letter is r, so the machine has no rule for it and the string does not match.
- In the text "color colour colr", the search finds 2 matches: "color" and "colour".
The pattern names two spellings and nothing else, which is why it is handy for search.
A server writes these lines to its log: ERROR timeout, ERROR refused, WARN timeout and ERROR disk. The pattern is (ERROR|WARN) timeout, which means "either ERROR or WARN, followed by a space and the word timeout". Find the lines it matches.
- Read the pattern. Its language is the union of the strings "ERROR timeout" and "WARN timeout".
- Test
ERROR timeout. It is the first option with the second word, so it matches. - Test
ERROR refused. The word after the space is refused, not timeout, so it does not match. - Test
WARN timeout. It is the second option with the second word, so it matches. - Test
ERROR disk. The second word is disk, so it does not match.
Try it: Using the same four lines, count how many match the pattern ERROR (timeout|refused), and say which lines they are.
Answer: Two lines match, ERROR timeout and ERROR refused. The WARN timeout line does not match because the pattern requires ERROR, and ERROR disk does not match because its word is not timeout or refused.
Common mistakes and tradeoffs
It is tempting to think that a pattern must match the whole string. In fact search tools usually look for a match anywhere in the text. The pattern ab* finds ab inside the string xabb. To require the whole string, the pattern must be anchored to the start and end of the line.
It is tempting to think that every pattern in a regex library is a regular language. In fact many engines support extra features, such as backreferences that require a repeated group to match the same text again. Those features go beyond regular languages, and they cost much more to match. The classic regular expressions in this lesson are the part that always runs in a single pass.
It is tempting to think that regular expressions can match nested structures, such as matching brackets in code or tags in HTML. In fact nesting needs a stack, which a finite state machine does not have. A pattern can check a single bracket, but not that every opening bracket has its closing partner at any depth. Use a context-free grammar and a parser for that job.
Regular expressions are a good choice for simple shapes and for tokenising, where the patterns are short and the speed matters. They are a poor choice for long, complicated patterns that are hard to read, and for untrusted input. Some engines backtrack, and a badly written pattern can take exponential time on a crafted string. Alternatives include a hand-written scanner, a parser generator, or an engine that guarantees linear time.
History
In 1951 Stephen Kleene introduced regular events as a way to describe the behaviour of simple machines. His 1956 paper showed that these descriptions match finite automata, which is the result this lesson rests on.
In 1968 Ken Thompson described a fast algorithm for regular-expression search that compiles the pattern into a state machine. It was used in the text editor qed and later in the Unix tools, including grep, which became a standard way to search text in the early 1970s.
The notation spread because it is short and precise. It is now built into most programming languages and editors, and it is the first stage of nearly every compiler, which is why a single idea from 1956 still runs inside tools used every day.
Recap
- A regular expression names a set of strings with symbols, concatenation, choice and repetition.
- Each regular expression has a state machine that accepts exactly the strings it names.
- Matching reads the string once, one symbol at a time, and only the current state matters.
- Regular expressions cannot count nested brackets, so nested structure needs a grammar.
- Read next: Lexical Analysis, where patterns like these turn source code into tokens, and Context-Free Grammar, which handles the nesting that patterns cannot.
Check yourself
QuestionWhat is the language of the pattern , in words?Show answer
It is the set of strings that begin with one followed by zero or more s: , , , and so on. The empty string and strings starting with are not in it.
QuestionHow many strings of length 3 over the alphabet match ?Show answer
A length-3 match must be followed by two s, because every match starts with and the rest must be s. That is only , so the answer is 1.
QuestionWhy can a state machine check without storing the whole string?Show answer
The machine only needs to know whether it has seen a valid prefix so far. After the first it is in an accepting state, and each keeps it there. It never needs to remember how many s it has read, so a fixed set of states is enough.
QuestionA pattern must match an HTML tag that opens and closes at any depth of nesting. Why can a single regular expression not do this reliably, and what would you use instead?Show answer
Matching nested opening and closing tags requires remembering how many are still open, which needs a stack. A finite state machine, and so a regular expression, has only a fixed set of states and no stack. A parser for a context-free grammar, which uses a stack, is the right tool.