Regular Expressions

Describing patterns in text

Paolo Rota

October 23, 2026

Where we are

in answers questions about exact text (Lecture 4):

print("nan" in "banana", "ing" in "singing", "ing" in "Ingrid")
True True False

Now try with in: a word that ends in -ing (singing yes, Ingrid no); an a followed, anywhere later, by a b; a date like 16/10/2026. Today:

  1. the language of patterns: what each symbol — *, +, ?, ., [...], … — asks the machine to do;
  2. the re functions that use a pattern: search, fullmatch, findall, sub, and groups;
  3. patterns on a real text, and from the command line.

These are not texts, they are patterns: descriptions of many possible texts at once. A regular expression (regex) is a small language for writing such descriptions. Python speaks it through the re module.

Your turn: find the dates

Before any new tool — with what you already know: loops, split, slicing, string methods.

text = "Exam on 16/12/2026, resit 20/01/2027. Office hours 14:30, room 1/2."

Problem: write find_dates(text), which returns every date written dd/mm/yyyy in the text. For this text:

['16/12/2026', '20/01/2027']

Hint: "2026".isdigit() is True when every character is a digit.

Your turn — two solutions

def find_dates(text):
    dates = []
    for word in text.split():
        word = word.strip(".,;:")
        if (len(word) == 10 and word[2] == "/" and word[5] == "/"
                and word[:2].isdigit() and word[3:5].isdigit()
                and word[6:].isdigit()):
            dates.append(word)
    return dates

print(find_dates(text))
['16/12/2026', '20/01/2027']
import re
print(re.findall(r"\d{2}/\d{2}/\d{4}", text))
['16/12/2026', '20/01/2027']

Ten lines of checks, or one line that describes a date: two digits, a slash, two digits, a slash, four digits. That one line is a regular expression — by the end of the lecture you will read it, and write it.

The hard way

Another question, solved the hard way for you: “an a, then a b somewhere after it”. Predict the four lines:

def a_then_b(s):
    i = 0
    while i < len(s) and s[i] != "a":     # walk to the first a
        i += 1
    while i < len(s) and s[i] != "b":     # from there, walk to a b
        i += 1
    return i < len(s)                     # did we stop on a b?

for w in ["albatross", "banana", "giant bear", "bat"]:
    print(w, a_then_b(w))
albatross True
banana False
giant bear True
bat False

The same question, as a pattern: a.*b. Four symbols, four questions:

a . * b
an a any one character the thing before, repeated any number of times — even zero a b

The language of patterns

Two testers

To study the symbols we need a way to try them. Two small functions, used as tools to try every symbol — what is inside them comes with the re functions:

import re

def check(pattern, texts):
    """For each text: does the WHOLE text fit the pattern?"""
    for t in texts:
        if re.fullmatch(pattern, t):
            print(f"  {pattern:<12} {repr(t):<10} yes")
        else:
            print(f"  {pattern:<12} {repr(t):<10} no")

def mark(pattern, text):
    """Print text with every match of the pattern in [brackets]."""
    print("  " + re.sub(pattern, lambda m: "[" + m.group() + "]", text))

Two questions you can ask with a pattern. check: is this whole text one of the texts the pattern describes? mark: where, inside this text, are the pieces it describes?

Symbols and concatenation

Most characters are symbols that stand for themselves: c matches the character c, and nothing else. Written one after another — concatenation — they must match in that order, with nothing in between. Predict:

check("cat", ["cat", "catt", "act", "Cat", "c at"])
mark("at", "the cat sat at the mat")
  cat          'cat'      yes
  cat          'catt'     no
  cat          'act'      no
  cat          'Cat'      no
  cat          'c at'     no
  the c[at] s[at] [at] the m[at]

cat is three questions in a row: a c? then an a? then a t? act has the right letters in the wrong order; Cat starts with a different character — C and c are two codes (Lecture 1). And mark finds at inside cat, sat and mat: a pattern sees characters; words mean nothing to it.

Union: |

| means or: red|blue matches red or blue. It has the lowest priority of all: it cuts the whole pattern in two, unless brackets keep it inside. Predict:

check("red|blue", ["red", "blue", "redblue", "re"])
check("gr(a|e)y", ["gray", "grey", "graey"])
check("gra|ey", ["gray", "gra", "ey"])
  red|blue     'red'      yes
  red|blue     'blue'     yes
  red|blue     'redblue'  no
  red|blue     're'       no
  gr(a|e)y     'gray'     yes
  gr(a|e)y     'grey'     yes
  gr(a|e)y     'graey'    no
  gra|ey       'gray'     no
  gra|ey       'gra'      yes
  gra|ey       'ey'       yes

gr(a|e)y is gr, then a or e, then y. Without brackets, gra|ey is gra or ey — the | swallowed everything on both sides. Brackets group, as in arithmetic: 2 + 3 * 4 against (2 + 3) * 4.

The star *: zero or more

* acts on the one thing just before it — a character, or a group in brackets — and means: that thing, repeated any number of times: 0, 1, 2, … How ab*c reads the text abbbc:

piece of the pattern a b* c
takes from abbbc a bbb — three times b c

Predict:

check("ab*c", ["ac", "abc", "abbbbc", "abab", "bc", "adc"])
check("(ab)*c", ["c", "abc", "ababc", "abbc"])
  ab*c         'ac'       yes
  ab*c         'abc'      yes
  ab*c         'abbbbc'   yes
  ab*c         'abab'     no
  ab*c         'bc'       no
  ab*c         'adc'      no
  (ab)*c       'c'        yes
  (ab)*c       'abc'      yes
  (ab)*c       'ababc'    yes
  (ab)*c       'abbc'     no

The star, case by case

Each text read against the pattern, piece by piece. One click per pattern:

ab*c — the star repeats only the b

text reading fits?
ac a, zero b, c yes
abc a, one b, c yes
abbbbc a, four b, c yes
abab a, b, then a c is needed: a no
bc the a has no star: required, missing no

(ab)*c — the star repeats the pair ab

text reading fits?
c zero pairs, c yes
abc one pair, c yes
ababc two pairs, c yes
abbc one pair, then a b: neither a pair nor the c no

A star can match nothing

Zero repetitions means x* also matches the empty text. mark shows an empty match as []. Predict:

check("a*", ["", "a", "aaaa", "b"])
mark("a*", "baad")
  a*           ''         yes
  a*           'a'        yes
  a*           'aaaa'     yes
  a*           'b'        no
  []b[aa][]d[]

a* matches the aa — and, between the other characters, nothing: zero as, successfully. Exactly what * promises.

'' zero as · a one · aaaa four · b: a* describes only texts made of as. On baad, position by position: before b, zero as → []; then [aa]; before d, zero → []; at the end, zero → [].

Zero repetitions, inside a text

check("(ab)*c", ["abbc"]) says no: the whole text does not fit. But mark looks inside the text. Predict:

mark("(ab)*c", "abbc")
mark("(ab)*c", "xxababc abc c")
  abb[c]
  xx[ababc] [abc] [c]

The whole of abbc does not fit, but a piece of it does: the lone c, with ab repeated zero times. Inside a text, a pattern that starts with x* takes whatever fits — even with no x at all. To require at least one, use +, one or more, instead of *: (ab)+c.

abbc, position by position. At 0: one pair ab, then a b — no c; zero pairs, then an a — no c. At 1 and 2: a b — no c. At 3: zero pairs, then c — the match. In xxababc abc c: ababc is two pairs + c, abc one pair + c, c zero pairs + c.

Union and star in real text

The same symbols, on texts you might really search. Predict where the brackets go:

mark("Alice|Rabbit", "The Rabbit ran, and Alice followed the Rabbit")
mark("go*al", "goal! gooooal! gal")
mark("ha(ha)*", "haha, hahahaha, ha!")
  The [Rabbit] ran, and [Alice] followed the [Rabbit]
  [goal]! [gooooal]! [gal]
  [haha], [hahahaha], [ha]!

Alice|Rabbit: either name, wherever it appears — three matches. go*al: g, any number of os, al — the commentator’s gooooal. ha(ha)*: one ha, then the pair repeated — a laugh of any length.

Look at gal and ha!: both fit, with zero repetitions. If you meant “at least one o” — a real goal — you need +, one or more: go+al.

Four operations

Everything so far — and every regular expression — is built from four operations:

Operation Written Matches
symbol a the character a itself
concatenation ab a followed by b
union a|b a or b
Kleene star a* a repeated zero or more times

Brackets group: (ab)* repeats ab, while ab* repeats only the b.

A finite pattern can describe an infinite set of texts: ab*c matches ac, abc, abbc, abbbc, … — every one of them.

More patterns to predict

Predict each line, then click:

check("(go)*", ["", "go", "gogo", "gog"])
check("1(0*)2", ["12", "102", "10002", "112"])
check("(c|d)*", ["", "cdcd", "ccd", "e"])
  (go)*        ''         yes
  (go)*        'go'       yes
  (go)*        'gogo'     yes
  (go)*        'gog'      no
  1(0*)2       '12'       yes
  1(0*)2       '102'      yes
  1(0*)2       '10002'    yes
  1(0*)2       '112'      no
  (c|d)*       ''         yes
  (c|d)*       'cdcd'     yes
  (c|d)*       'ccd'      yes
  (c|d)*       'e'        no

Read a pattern from left to right, like the machine: 1(0*)2 is a 1, then any number of 0s, then a 2. 112 fails because the second 1 is neither a 0 nor the 2.

More patterns, case by case

pattern text reading fits?
(go)* '' / go / gogo zero / one / two pairs go yes
(go)* gog one pair, then a g alone, half a pair no
1(0*)2 12 / 102 / 10002 1, zero / one / three 0, 2 yes
1(0*)2 112 after the 1 comes a 0 or the 2 — here a 1 no
(c|d)* '' zero choices yes
(c|d)* cdcd / ccd a new choice each time: c d c d, c c d yes
(c|d)* e e is neither c nor d no

In 1(0*)2 the brackets change nothing: 0 is already one character, so 10*2 is the same pattern. Brackets matter only to repeat more than one character, as in (go)*.

Shortcuts

One or more, or optional: + and ?

Like *, they act on the one thing just before them — shortcuts for the four operations:

Written Means Same as
x+ one or more x: like *, but never zero xx*
x? x or nothing: optional (x|)

Predict:

check("ba+", ["b", "ba", "baaa"])
check("colou?r", ["color", "colour", "colouur"])
mark("a+", "baad")
  ba+          'b'        no
  ba+          'ba'       yes
  ba+          'baaa'     yes
  colou?r      'color'    yes
  colou?r      'colour'   yes
  colou?r      'colouur'  no
  b[aa]d

b fails: + wants at least one a. colouur fails: ? allows one u or none, never two. And a+ marks only the aa — no empty matches.

Exact counts: {m,n}

Curly brackets give the number of repetitions — of the one thing just before them, as always:

Written Means Same as
x{3} exactly 3 x xxx
x{2,4} from 2 to 4 x (xx|xxx|xxxx)
x{2,} 2 or more x xxx*

Predict:

check("ha{2,3}", ["ha", "haa", "haaa", "haaaa"])
check("(ha){2}", ["haha", "haa", "hahaha"])
  ha{2,3}      'ha'       no
  ha{2,3}      'haa'      yes
  ha{2,3}      'haaa'     yes
  ha{2,3}      'haaaa'    no
  (ha){2}      'haha'     yes
  (ha){2}      'haa'      no
  (ha){2}      'hahaha'   no

ha{2,3} repeats only the a: haa, haaa. To repeat the whole ha, brackets: (ha){2} is haha, and nothing else.

+, ? and {m,n} in real text

Predict where the brackets go:

mark("no+", "no, nooo, nooooo!")
mark("no{3,}", "no, nooo, nooooo!")
mark("colou?r", "color or colour?")
mark("Mrs?", "Mr Smith and Mrs Rossi")
  [no], [nooo], [nooooo]!
  no, [nooo], [nooooo]!
  [color] or [colour]?
  [Mr] Smith and [Mrs] Rossi

no+: n, then one or more os — every no, however long. no{3,}: at least three os — only the emphatic ones. colou?r: the American and the British spelling with one pattern. Mrs?: Mr, with an optional s — both titles.

Each symbol answers how many times for the one thing just before it: the o in no+, the u in colou?r, the s in Mrs?.

Halfway: write the pattern (1/2)

Only the symbols so far: |, *, +, ?, {m,n} and brackets. Write the pattern, then click.

text = "ha, haha, hahaha, h!"

Problem: mark every laugh — but not the lone h.

mark("(ha)+", text)
  [ha], [haha], [hahaha], h!

ha, one or more times: the brackets make ha one thing for the +. ha+ would mean haaaa.

text = "ciao, ciaooo, ciaooooo, cia"

Problem: mark every ciao, however long — but not cia.

mark("ciao+", text)
  [ciao], [ciaooo], [ciaooooo], cia

cia, then one or more o: + refuses zero, so cia stays out.

Halfway: write the pattern (2/2)

text = "hm, hmm, hmmm, hmmmmm"

Problem: mark only the long thinking noises: h and at least three m.

mark("hm{3,}", text)
  hm, hmm, [hmmm], [hmmmmm]
text = "Mr Rossi, Mrs Bianchi, Ms Verdi, Dr Neri"

Problem: mark every title — whole.

mark("Mr|Mrs|Ms|Dr", text)
mark("Mrs?|Ms|Dr", text)
  [Mr] Rossi, [Mr]s Bianchi, [Ms] Verdi, [Dr] Neri
  [Mr] Rossi, [Mrs] Bianchi, [Ms] Verdi, [Dr] Neri

The first try marks only Mr of Mrs: the alternatives are tried in order, and Mr already fits. Mrs? takes the s when there is one.

Any character: .

. matches exactly one character, whatever it is: letter, digit, space, punctuation — anything but a newline. Predict:

check("c.t", ["cat", "cot", "c t", "c.t", "ct", "cart"])
mark("c.t", "cat, cut, c3t, ct")
mark("h.t", "hat, hot, hit, heat, h t")
  c.t          'cat'      yes
  c.t          'cot'      yes
  c.t          'c t'      yes
  c.t          'c.t'      yes
  c.t          'ct'       no
  c.t          'cart'     no
  [cat], [cut], [c3t], ct
  [hat], [hot], [hit], heat, [h t]

Exactly one: ct has no character between c and t, cart — and heat in the sentence — have two. The space of h t is a character too. c.t accepts a real c.t — but also everything else. To mean only the dot, write \.: a \ before a special symbol makes it a plain character.

.*: anything at all

. (any character) with * (any number of times): .* is any text, of any length — even none. Alone it is useless: “anything” fits everything. Its job is between two fixed pieces, when you know how something starts and ends but not what is inside. a.*b is one: an a, anything, a b. An HTML tag is another: <, anything, >. Predict:

mark("a.*b", "bat")
mark("a.*b", "albatross")
mark("<.*>", "<b>")
mark("<.*>", "Say <b>hi</b> now")
  bat
  [alb]atross
  [<b>]
  Say [<b>hi</b>] now

bat: no b after the a — no match, as a_then_b said. albatross: a, then l as the .*, then the b. <b>: <, then b as the .*, then > — one tag, whatever its name.

The last line is not two tags but one match, from the first < to the last >. * is greedy: .* first swallows the whole rest of the text, then gives characters back one by one until the > can match — at the last >.

Greedy and lazy

* and + take as much as they can. Add a ? after them — *?, +? — and they take as little as they can. Predict the four lines:

mark("<.*>", "Say <b>hi</b> now")
mark("<.*?>", "Say <b>hi</b> now")

text = 'She said "yes" and then "no".'
mark('".*"', text)
mark('".*?"', text)
  Say [<b>hi</b>] now
  Say [<b>]hi[</b>] now
  She said ["yes" and then "no"].
  She said ["yes"] and then ["no"].

Greedy .* runs to the last > (or ") it can reach: one match, with everything in between. Lazy .*? stops at the first one that lets the match end: one match per tag, one per quotation.

Sets of characters: [...]

Square brackets stand for one character, chosen from a set:

Written Means
[aeiou] one of these characters: same as (a|e|i|o|u)
[a-z] one character in this range
[A-Za-z0-9] several ranges in one set
[^aeiou] one character not in the set

Inside [...], . * ? are plain characters. Predict:

check("b[aeiou]t", ["bat", "bit", "bt", "boot"])
check("[A-Z][a-z]+", ["Alice", "alice", "A"])
mark("[aeiou]+", "queueing in Trento")
mark("[^aeiou ]+", "queueing in Trento")
  b[aeiou]t    'bat'      yes
  b[aeiou]t    'bit'      yes
  b[aeiou]t    'bt'       no
  b[aeiou]t    'boot'     no
  [A-Z][a-z]+  'Alice'    yes
  [A-Z][a-z]+  'alice'    no
  [A-Z][a-z]+  'A'        no
  q[ueuei]ng [i]n Tr[e]nt[o]
  [q]ueuei[ng] i[n] [Tr]e[nt]o

Classes of characters

Three sets are used so often that they have a letter:

Written Means
\d a digit (0–9, and the digits of other scripts)
\w a “word” character: letter, digit or _
\s white space: space, tab, newline, …
\D \W \S the opposite of each
mark(r"\d+", "Room 214, floor 2, built 1998")
mark(r"\w+", "Città: Trento — perché no?")
  Room [214], floor [2], built [1998]
  [Città]: [Trento] — [perché] [no]?

\w knows accented letters: Città and perché come out whole. Note the r before the quotes: a raw string, so that Python leaves the \ alone.

Sets and classes in real text

Predict where the brackets go:

mark("[A-Z][a-z]+", "Alice met the Queen of Hearts")
mark("[0-9]{4}", "born 1998, room 214, year 2026")
mark(r"\d{2}:\d{2}", "lunch 12:30, class 9:00 and 14:30")
  [Alice] met the [Queen] of [Hearts]
  born [1998], room 214, year [2026]
  lunch [12:30], class 9:00 and [14:30]

[A-Z][a-z]+: a capital, then lower-case letters — the capitalised words, a first guess at names. [0-9]{4}: exactly four digits — the years; 214 has only three. \d{2}:\d{2}: two digits, a colon, two digits — a time.

9:00 is missed: one digit before the colon, and the pattern asked for two. A pattern finds exactly what it describes — \d{1,2}:\d{2} would take it.

Raw strings: r"..."

In a Python string, \ already means something: "\n" is a newline, "\t" a tab (Lecture 3, and the Windows path trap of Lecture 6). Put an r in front — a raw string — and a \ is just a backslash. Predict:

print("C:\new\table")
print(r"C:\new\table")
print(len("\n"), len(r"\n"))
C:
ew  able
C:\new\table
1 2

Without the r, Python changes the text before anyone else sees it: \n became a new line, \t a tab. Regex patterns are full of \ — \d, \w, \s, \. — and they must reach re exactly as you typed them. Always write patterns as r"...": one letter, no surprises.

Anchors and literal symbols

^ matches at the start of the text, $ at the end — positions, not characters. To match a character that has a special meaning — ., *, ?, (, … — put a \ before it. Predict which names get brackets:

names = ["sub-01.json", "sub-02.nii", "notes.json.bak", "sub-03_json"]

for name in names:
    mark(r"^sub-\d+\.json$", name)
  [sub-01.json]
  sub-02.nii
  notes.json.bak
  sub-03_json

Only the first. $ rejects notes.json.bak (text after json), ^ would reject anything before sub, and \. is a real dot: without the \, the . would match any character, and sub-03_json would slip through.

Whole words: \b

\b is a word boundary: the edge of a word, where a letter or digit meets a space, punctuation, or the start or end of the text. Like ^ and $, it matches a position: the place between two characters. Predict:

mark("cat", "cat, cats, concatenate, the cat")
mark(r"\bcat\b", "cat, cats, concatenate, the cat")
  [cat], [cat]s, con[cat]enate, the [cat]
  [cat], cats, concatenate, the [cat]

Without \b, cat is found inside cats and concatenate: a pattern sees only characters. With \b on both sides, only the whole word cat.

The language, on one slide

Written Means
abc a, then b, then c
a|b a or b
( ) one piece, to repeat or choose
x* x, 0 or more times
x+ x, 1 or more times
x? x or nothing
x{m,n} x, from m to n times
Written Means
. any one character
[ab] [a-z] one character of a set
[^ab] one character not in it
\d \w \s digit, word char., space
\b ^ $ boundary, start, end
\. \* … the character itself
*? +? lazy: as little as possible

Repetitions — * + ? {m,n} — always act on the one thing just before them. To repeat more than one character, put brackets around it.

Using patterns: the re functions

re.search

re.search(pattern, text) looks for the first place where the pattern matches. It returns a match object if it finds one, None if not. Predict the second line:

m = re.search(r"a.*b", "the albatross")
print(m)
print(re.search(r"a.*b", "banana"))
<re.Match object; span=(4, 7), match='alb'>
None

Since None counts as False and a match object as True (Lecture 3), the usual shape is an if:

for text in ["giant bear", "big cat"]:
    if re.search(r"a.*b", text):
        print(text, "-> match")
    else:
        print(text, "-> no match")
giant bear -> match
big cat -> no match

search does not return True or False. It returns an object — or None. Same pattern as x is None in Lecture 3.

What a match object knows

A match object is an object like those of Lecture 8: it has methods.

m = re.search(r"a.*b", "the albatross is above")

print(m.group())       # the text that matched
print(m.start(), m.end())
print(m.span())
albatross is ab
4 19
(4, 19)

Two rules decide which text matches: the match starts as early as possible — at the first a; and * is greedy — it runs to the last b it can reach.

re.fullmatch: the whole text

search is happy with a match anywhere inside. re.fullmatch asks whether the whole text fits — the question check has been asking all along. Predict:

print(re.search(r"\d+", "year 2026"))
print(re.fullmatch(r"\d+", "year 2026"))
print(re.fullmatch(r"\d+", "2026"))
<re.Match object; span=(5, 9), match='2026'>
None
<re.Match object; span=(0, 4), match='2026'>

Testing input — is this a number? a date? a subject label? — is a fullmatch question. Finding something in a longer text is a search question.

re.findall: every match

findall returns a list of every match, left to right, without overlaps. No match: an empty list (search gave None). Predict the last two lines:

print(re.findall(r"a", "abracadabra"))
print(re.findall(r"ab", "abracadabra"))
print(re.findall(r"z", "abracadabra"))
print(len(re.findall(r"the", "the cat and the other hat")))
print(len(re.findall(r"\bthe\b", "the cat and the other hat")))
['a', 'a', 'a', 'a', 'a']
['ab', 'ab']
[]
3
2

search answers “is it there, and where?”; findall answers “what are all of them?” — and len of the list counts them.

Upper and lower case

Patterns are case-sensitive, like ==. Either lower the text first, or tell re to ignore case with a flag:

text = "Alice said: alice is ALICE."

print(re.findall(r"alice", text))
print(re.findall(r"alice", text.lower()))
print(re.findall(r"alice", text, flags=re.IGNORECASE))
['alice']
['alice', 'alice', 'alice']
['Alice', 'alice', 'ALICE']

re.sub: replace every match

re.sub(pattern, replacement, text) returns a new string in which every match is replaced — strings never change (Lecture 3). Predict:

print(re.sub(r"\bteh\b", "the", "teh cat, tehnically, saw teh fish"))
print(re.sub(r"[.,;:!?]", "", "Well, well... Hello!"))
print(re.sub(r"\s+", " ", "too    many     spaces"))
the cat, tehnically, saw the fish
Well well Hello
too many spaces

The replacement can also be a function of the match: mark is one re.sub that turns each match m into "[" + m.group() + "]". Both testers are now open. More of sub in Lecture 10.

Groups

Brackets do a second job: they capture the part they enclose. The match object gives it back with group(1), group(2), …

m = re.search(r"(\d{2})/(\d{2})/(\d{4})", "Exam on 16/12/2026, room B")

print(m.group())                       # the whole match
print(m.group(1), m.group(2), m.group(3))
print(m.groups())                      # all of them, as a tuple
16/12/2026
16 12 2026
('16', '12', '2026')
m = re.search(r"^(\w+)ing$", "singing")
print(m.group(1))                      # the stem, without -ing
sing

findall with groups

With groups in the pattern, findall returns what the groups captured instead of the whole match:

text = "Sessions: 16/10/2026, 23/10/2026 and 30/10/2026."

print(re.findall(r"\d{2}/\d{2}/\d{4}", text))         # no groups: whole match
print(re.findall(r"(\d{2})/\d{2}/\d{4}", text))       # one group: strings
print(re.findall(r"(\d{2})/(\d{2})/(\d{4})", text))   # several: tuples
['16/10/2026', '23/10/2026', '30/10/2026']
['16', '23', '30']
[('16', '10', '2026'), ('23', '10', '2026'), ('30', '10', '2026')]

No groups → list of whole matches. One group → list of that group. Several groups → list of tuples, one per match. The tuples unpack in a for, as in Lectures 3–4: for day, month, year in ....

Patterns on a real text

Counter, a reminder

From Lecture 7: Counter, from the module collections, counts the items of a list — the quickest way to count the words of a whole book.

from collections import Counter

votes = ["red", "blue", "red", "green",
         "red", "blue"]
counts = Counter(votes)

print(counts["red"], counts["purple"])
print(counts.most_common(2))
print(len(counts), "different colours")
for colour, n in counts.most_common():
    print(colour, n)
3 0
[('red', 3), ('blue', 2)]
3 different colours
red 3
blue 2
green 1
You write You get
Counter(items) the count of each different item
counts[x] how many times x appeared — 0 if never
counts.most_common(2) the top 2, as (item, count) pairs
counts.most_common() all of them, most frequent first
len(counts) how many different items

Lecture 8’s Book, on the whole book

Book lives in texts.py since Lecture 8. Its words() splits at spaces and strips punctuation from the two ends of each piece. On the whole of resources/alice.txt (Lecture 6), predict: how many alice, and is * a word?

from collections import Counter
from texts import Book

alice = Book("resources/alice.txt")
counts = Counter(alice.words())

print(len(alice.lines), "lines,", len(alice.words()), "words")
print(counts["alice"], counts["alice’s"], counts["*"], counts["_very_"])
3384 lines, 26525 words
385 12 60 14

Stripping the ends says what a word is not, one character at a time — and misses what sits inside (alice’s) or was not on the list (*, the _ of italics). A pattern says what a word is.

The words of a book, properly

Lecture 8’s way to get “the same, but different”: inherit, and override words() with a pattern — [a-z]+, a run of letters:

class RegexBook(Book):
    def words(self):
        """Return every run of letters, lower-cased."""
        return re.findall(r"[a-z]+", " ".join(self.lines).lower())

alice = RegexBook("resources/alice.txt")
counts = Counter(alice.words())

print(len(alice.words()), "words")
print(counts["alice"], counts["*"], counts["very"])
print(alice.words()[-8:])
27427 words
399 0 144
['life', 'and', 'the', 'happy', 'summer', 'days', 'the', 'end']

__init__ and lines come from Book unchanged; only words() is new. Every program that asks a RegexBook for its words gets the better answer.

Asking the book questions

The whole book as one string, then one pattern per question:

text = " ".join(alice.lines)

print(len(re.findall(r"\bAlice\b", text)))                 # the name
ing = re.findall(r"\b\w+ing\b", text)                      # -ing words
print(len(ing), ing[:6])
print(re.findall(r"\b[A-Z][a-z]+\b", text)[:8])            # capitalised
print(re.findall(r"\b\w{4}\b", text)[:8])                  # 4-letter words
398
915 ['beginning', 'sitting', 'having', 'nothing', 'reading', 'considering']
['Illustration', 'Alice', 'Adventures', 'Wonderland', 'Lewis', 'Carroll', 'Contents', 'Down']
['Down', 'Hole', 'Pool', 'Race', 'Long', 'Tale', 'Bill', 'from']

Each question is one line. Writing each as a loop over characters, like a_then_b, would be a function of its own — and a new chance for a bug.

A pattern from the command line

Lecture 6’s argparse and today’s re, in one small tool: give it a pattern and a file, and it prints the lines that match, with their numbers.

# find.py
"""Print the lines of a file that match a pattern."""
import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument("pattern", help="a regular expression")
parser.add_argument("path", help="the file to search")
args = parser.parse_args()

number = 0
with open(args.path, "r", encoding="utf-8") as f:
    for line in f:
        number += 1
        if re.search(args.pattern, line):
            print(f"{number:>4}: {line.rstrip()}")

A pattern from the command line — run

Three questions to the whole book. Predict what each run prints:

(intro2python) $ python find.py '\bWonderland\b' resources/alice.txt
   1: The Project Gutenberg eBook of Alice's Adventures in Wonderland
  11: Title: Alice's Adventures in Wonderland
  34: Alice’s Adventures in Wonderland
3388: Wonderland, though she knew she had but to open them again, and all
3403: perhaps even with the dream of Wonderland of long ago: and how she
(intro2python) $ python find.py 'Curiouser' resources/alice.txt
 281: “Curiouser and curiouser!” cried Alice (she was so much surprised, that
(intro2python) $ python find.py '^\*\*\*' resources/alice.txt
  27: *** START OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***
3412: *** END OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND ***

Put the pattern in single quotes: the terminal then passes the \ and the * to Python untouched, as one argument.

What to take away

  1. A pattern is read left to right, one question per symbol. Four operations — symbol, concatenation, union |, star * — plus shortcuts: + ? {m,n}, ., [...], \d \w \s, \b ^ $.
  2. * + ? {m,n} repeat the one thing just before them; ( ) makes a piece one thing. * allows zero, and is greedy; *? is lazy.
  3. Always r"..."; \. for a literal dot.
  4. re.search → match object or None; re.fullmatch → the whole text; re.findall → list of every match; re.sub → a new string.
  5. ( ) capture: m.group(1); findall returns groups, or tuples of groups. Check for None before you ask a match for its group().

Try it now

Try it 1 — Email addresses

text = "Write to anna.rossi@unitn.it or to help@lab.org, not to @nobody."

Problem: list every email address in text — and not @nobody.

print(re.findall(r"[\w.]+@[\w.]+\.\w+", text))
['anna.rossi@unitn.it', 'help@lab.org']

Letters, digits or dots, then @, then more of them, then a real dot and the ending. [\w.]+ needs at least one character before the @: the space before @nobody is not one.

Try it 2 — The bill

text = "Coffee 1.20 EUR, croissant 1.50 EUR, water 0.90 EUR, table 4."

Problem: how much is the bill? Find every price, then add them up.

prices = re.findall(r"\d+\.\d{2}", text)
total = 0
for p in prices:
    total = total + float(p)
print(prices, round(total, 2))
['1.20', '1.50', '0.90'] 3.6

Digits, a real dot, exactly two digits: table 4 is not a price. findall returns strings — float() turns each into a number (Lecture 3).

Try it 3 — Hashtags and mentions

text = "Great talk by @prota on #regex and #Python! cc @anna"

Problem: list the hashtags, then the people mentioned — two lists.

print(re.findall(r"#\w+", text))
print(re.findall(r"@\w+", text))
['#regex', '#Python']
['@prota', '@anna']

The symbol, then one or more word characters: \w+ stops at the ! and at the spaces.

Try it 4 — Stage directions

text = "ALICE: (sighing) I'm so tired. RABBIT: (looking at his watch) Late! Late!"

Problem: remove the stage directions in brackets — keep only what is said.

print(re.sub(r" \(.*?\)", "", text))
print(re.sub(r" \(.*\)", "", text))           # greedy: too much
ALICE: I'm so tired. RABBIT: Late! Late!
ALICE: Late! Late!

A space, a real (, anything — lazy — and a real ). The greedy .* runs from the first ( to the last ), and Alice’s line disappears with it.

Try it 5 — Missing values

lines = ["sub-01 rt=512", "sub-02 rt=498", "sub-03 no response", "sub-04 rt=530"]

Problem: for each line, print the subject and its reaction time as a number — or missing.

for line in lines:
    m = re.search(r"rt=(\d+)", line)
    subject = line.split()[0]
    if m:
        print(subject, int(m.group(1)))
    else:
        print(subject, "missing")
sub-01 512
sub-02 498
sub-03 missing
sub-04 530

search returns None on sub-03, and None has no group: test first, then ask for the group. Without the if, the loop stops with an AttributeError on the third line.

Exercises

Exercise 1 — Predict, then check

For each pattern, say which texts match as a whole. Then check with the check function from the slides.

Pattern Texts
m m, mm, man, n
A3b A3b, A3, 3bA, a3b
red|blue red, blue, redblue, green
(go)* (empty), go, gogo, gog, o
1(0*)2 12, 102, 10002, 112, 1020
(c|d)* (empty), c, cdcd, ccd, e

Exercise 1 — solution (1/2)

check(r"m", ["m", "mm", "man", "n"])
check(r"A3b", ["A3b", "A3", "3bA", "a3b"])
check(r"red|blue", ["red", "blue", "redblue", "green"])
  m            'm'        yes
  m            'mm'       no
  m            'man'      no
  m            'n'        no
  A3b          'A3b'      yes
  A3b          'A3'       no
  A3b          '3bA'      no
  A3b          'a3b'      no
  red|blue     'red'      yes
  red|blue     'blue'     yes
  red|blue     'redblue'  no
  red|blue     'green'    no

Exercise 1 — solution (2/2)

check(r"(go)*", ["", "go", "gogo", "gog", "o"])
check(r"1(0*)2", ["12", "102", "10002", "112", "1020"])
check(r"(c|d)*", ["", "c", "cdcd", "ccd", "e"])
  (go)*        ''         yes
  (go)*        'go'       yes
  (go)*        'gogo'     yes
  (go)*        'gog'      no
  (go)*        'o'        no
  1(0*)2       '12'       yes
  1(0*)2       '102'      yes
  1(0*)2       '10002'    yes
  1(0*)2       '112'      no
  1(0*)2       '1020'     no
  (c|d)*       ''         yes
  (c|d)*       'c'        yes
  (c|d)*       'cdcd'     yes
  (c|d)*       'ccd'      yes
  (c|d)*       'e'        no

(go)*: zero, one, two pairs fit · gog leaves a g alone · o is not a pair. 1(0*)2: zero, one, three 0s fit · 112: a 1 where a 0 or the 2 must be · 1020: 102 fits, but a 0 is left over. (c|d)*: any sequence of cs and ds, even empty · e is neither.

Exercise 2 — One word, many patterns

Use re.search to test the word "pancake" against each pattern below. For each, print the pattern, whether it matched, and if so what group() returns.

patterns = [r"a|b", r"a*", r"(pn)*", r"an", r"^p", r"e$", r"c.k", r"[^aeiou]+"]

Two of the results look like “no match” at first sight. Which, and why are they matches?

Exercise 2 — solution

patterns = [r"a|b", r"a*", r"(pn)*", r"an", r"^p", r"e$", r"c.k", r"[^aeiou]+"]

for p in patterns:
    m = re.search(p, "pancake")
    if m:
        print(f"{p:<10} match  {repr(m.group())}")
    else:
        print(f"{p:<10} no match")
a|b        match  'a'
a*         match  ''
(pn)*      match  ''
an         match  'an'
^p         match  'p'
e$         match  'e'
c.k        match  'cak'
[^aeiou]+  match  'p'

a* and (pn)* match the empty string at position 0: zero repetitions are allowed, and search takes the earliest match it can find — even an empty one. With fullmatch both would fail.

Exercise 3 — Counting in a book

Write three functions, each taking the text of a book as one string — " ".join(book.lines) of a Book:

  • count_word(text, word) — how many times word appears as a whole word, case-sensitive;
  • count_word_any_case(text, word) — the same, ignoring case;
  • ing_words(text) — the list of distinct words ending in -ing, lower-cased and sorted.

Test them on resources/alice.txt: how many Alice, how many alice, and how many distinct -ing words?

Exercise 3 — solution

def count_word(text, word):
    """Return how many times word appears as a whole word."""
    return len(re.findall(r"\b" + word + r"\b", text))

def count_word_any_case(text, word):
    """Like count_word, ignoring upper and lower case."""
    return len(re.findall(r"\b" + word + r"\b", text, flags=re.IGNORECASE))

def ing_words(text):
    """Return the distinct words ending in -ing, lower-cased and sorted."""
    return sorted(set(re.findall(r"\b\w+ing\b", text.lower())))

text = " ".join(Book("resources/alice.txt").lines)
print(count_word(text, "Alice"), count_word(text, "alice"),
      count_word_any_case(text, "alice"))
print(len(ing_words(text)), ing_words(text)[:6])
398 0 398
264 ['accounting', 'adding', 'addressing', 'anything', 'appearing', 'asking']

A pattern is just a string, so it can be built with +. set removes the repeats and sorted orders them (Lecture 3).

Exercise 4 — Validators

Write four functions that return True or False:

  • is_number(s) — only digits, at least one: "2024" yes, "20a4" no;
  • is_word(s) — only letters a–z or A–Z: "cat" yes, "cat5" no;
  • is_capitalised(s) — starts with a capital letter: "Trento" yes;
  • is_subject(s) — a BIDS subject label: sub- and two digits, "sub-07".

Test each on at least two texts that should pass and two that should not.

Exercise 4 — solution

def is_number(s):
    return re.fullmatch(r"\d+", s) is not None

def is_word(s):
    return re.fullmatch(r"[a-zA-Z]+", s) is not None

def is_capitalised(s):
    return re.search(r"^[A-Z]", s) is not None

def is_subject(s):
    return re.fullmatch(r"sub-\d{2}", s) is not None

print(is_number("2024"), is_number("20a4"), is_number(""))
print(is_word("cat"), is_word("cat5"), is_word("Città"))
print(is_capitalised("Trento"), is_capitalised("trento"))
print(is_subject("sub-07"), is_subject("sub-7"), is_subject("sub-007"))
True False False
True False False
True False
True False False

... is not None turns the match object into a real True/False. Città is not a word here: [a-zA-Z] has no à.

Exercise 5 — Vowels, digits, dates

Three small functions, each one findall long:

  • count_vowels(text) — the number of vowels, upper or lower case;
  • digits_only(text) — a new string with only the digits of text: "Room 214, floor 2" → "2142";
  • find_dates(text) — every date written dd/mm/yyyy, as a list of (day, month, year) tuples of integers.

Exercise 5 — solution

def count_vowels(text):
    return len(re.findall(r"[aeiou]", text, flags=re.IGNORECASE))

def digits_only(text):
    return "".join(re.findall(r"\d", text))

def find_dates(text):
    dates = []
    for day, month, year in re.findall(r"\b(\d{2})/(\d{2})/(\d{4})\b", text):
        dates.append((int(day), int(month), int(year)))
    return dates

print(count_vowels("Appalachicola"), digits_only("Room 214, floor 2"))
print(find_dates("From 16/10/2026 to 30/10/2026, not 1/1/26."))
6 2142
[(16, 10, 2026), (30, 10, 2026)]

findall hands back strings, even for \d: the int(...) is the step that makes them numbers, as with input().

Exercise 6 — Taking BIDS names apart

BIDS file names follow a pattern: sub-<label>_task-<label>_<suffix>.<ext>.

In a module bids.py, write parse_bids(name) that returns a dictionary with keys sub, task, suffix, ext — or None if the name does not follow the pattern.

parse_bids("sub-01_task-rest_bold.json")
# {'sub': '01', 'task': 'rest', 'suffix': 'bold', 'ext': 'json'}
parse_bids("notes.txt")     # None

Labels are letters and digits; suffix and extension are lower-case, and the extension may contain a dot, as in nii.gz.

In main.py, import it and print, for a list of file names, the subject and task of each BIDS name — and skip the others.

Exercise 6 — solution

# bids.py
"""Take BIDS file names apart."""
import re

PATTERN = r"sub-([a-zA-Z0-9]+)_task-([a-zA-Z0-9]+)_([a-z]+)\.([a-z.]+)"


def parse_bids(name):
    """Return sub, task, suffix and ext of a BIDS name, or None."""
    m = re.fullmatch(PATTERN, name)
    if m is None:
        return None
    return {"sub": m.group(1), "task": m.group(2),
            "suffix": m.group(3), "ext": m.group(4)}

One group per piece you want back. \. is a real dot; inside [...] a . is already literal, so [a-z.]+ accepts nii.gz. if m is None comes before m.group: None has no group.

Exercise 6 — solution, run

# main.py
from bids import parse_bids

names = ["sub-01_task-rest_bold.json", "sub-12_task-nback_bold.nii.gz",
         "sub-01_rest_bold.json", "notes.txt"]

for name in names:
    parts = parse_bids(name)
    if parts is None:
        print(f"skipped    {name}")
    else:
        print(f"sub-{parts['sub']}  {parts['task']:<6} {name}")
(intro2python) $ python main.py
sub-01  rest   sub-01_task-rest_bold.json
sub-12  nback  sub-12_task-nback_bold.nii.gz
skipped    sub-01_rest_bold.json
skipped    notes.txt

main.py never sees a pattern: it asks bids.py for the pieces, and None tells it which names to skip.

Questions?