impera Open Impera

A levels Computer Science · Theory of computation

Regular expressions

1Sets and languages

A set is an unordered collection of different items, for example A = {1, 2, 3}.

  • Set comprehension describes a set by a rule: {x | x ∈ ℕ and x < 5} = {0, 1, 2, 3, 4}.
  • The empty set is {} or Ø.
  • Union A ∪ B, intersection A ∩ B, difference A \ B.
  • The Cartesian product A × B is the set of all ordered pairs (a, b). If A = {x, y} and B = {1, 2}, A × B = {(x,1), (x,2), (y,1), (y,2)}.

A language is a set of strings made from an alphabet. For example, all binary strings that start with 1 form a language over the alphabet {0, 1}.

Check yourself

If A = {1, 2, 3} and B = {2, 3, 4}, what is A ∩ B?

  • {2, 3}

  • {4}

  • {1, 2, 3, 4}

  • {1}

Show the answer

{2, 3}

In both.

2Regular expression notation

A regular expression (regex) is a short way of describing a set of strings.

SymbolMeaningExampleMatches
athe character acatcat
|ora|ba, b
*zero or more of the previous itemab*a, ab, abb, ...
+one or moreab+ab, abb, ...
?zero or onecolou?rcolor, colour
( )groups items(ab)*(empty), ab, abab, ...
Check yourself

Which strings does a(bc)* match?

  • bc, bcbc, ...

  • a, ab, ac

  • a, abc, abcbc, ...

  • abc only

Show the answer

a, abc, abcbc, ...

Group repeats.

3Reading and writing regular expressions

Worked example

Describing languages

  1. Binary strings that start with 1: 1(0|1)*.
  2. Binary strings with at least one 0: (0|1)0(0|1).
  3. Strings of a's with an even number of a's: (aa)*.
  4. "grey" or "gray": gr(e|a)y.
Worked example

Does 0110 match 0(1|0)*0?

  1. It starts with 0: yes.
  2. The middle part "11" matches (1|0)*: yes.
  3. It ends with 0: yes. So it matches.
Check yourself

Does 101 match 1(01)+?

  • No, + needs two copies

  • No, it must start with 0

  • Only if it is longer

  • Yes

Show the answer

Yes

1 then one copy of 01.

4Regular expressions and FSMs

Every regular expression can be turned into an FSM that accepts the same strings, and every FSM can be described by a regular expression. Both describe the regular languages.

The FSM for the regular expression ab*c. The a and c are single transitions; b* becomes a loop that can be taken any number of times.

Each part of the regex becomes part of the machine: a single character is one transition, * becomes a loop, and | becomes a choice of transitions.

Check yourself

What does the * in a regular expression become in an FSM?

  • An accepting state

  • A dead end

  • A new alphabet

  • A loop back to a state

Show the answer

A loop back to a state

Repeat any number of times.

5Regular expressions in practice

Programming languages use extended regex syntax for validating and searching text:

PatternMeaning
[0-9] or \dany digit
[A-Z]any capital letter
{3}exactly three of the previous item
^ and $start and end of the string
.any single character
import re
pattern = r"^[A-Z]{2}[0-9]{4}$"       # two capitals then four digits
print(bool(re.match(pattern, "AB1234")))   # True
print(bool(re.match(pattern, "A12345")))   # False

Uses: validating form input (postcodes, dates), search and replace in editors, and the lexical analysis stage of compilers.

Check yourself

Which string matches ^[0-9]{3}-[0-9]{2}$?

  • 12-345

  • 1234-5

  • abc-de

  • 123-45

Show the answer

123-45

Three digits, dash, two digits.

6Beyond regular languages: BNF

Some languages cannot be described by a regular expression, such as balanced brackets or arithmetic expressions with nesting. These need a context-free description.

Backus–Naur form (BNF) defines a language with rules:

  • <digit> ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  • <integer> ::= <digit> | <digit><integer>
  • <expr> ::= <integer> | ( <expr> + <expr> )

The rule for <integer> is recursive: it is defined in terms of itself, which lets it describe strings of any length. Syntax diagrams show the same rules as railway-track pictures.

BNF is used to define the syntax of programming languages, and the parser in a compiler checks code against it.

Check yourself

Why can BNF describe nested brackets when a regular expression cannot?

  • BNF has more symbols available, so it can describe more brackets

  • BNF rules can be recursive, so they can nest to any depth

  • BNF only describes numbers, which are simpler than brackets

  • Regular expressions cannot use bracket characters at all

Show the answer

BNF rules can be recursive, so they can nest to any depth

Self-reference.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera