Describing patterns in text
October 23, 2026
in answers questions about exact text (Lecture 4):
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:
*, +, ?, ., [...], … — asks the machine to do;re functions that use a pattern: search, fullmatch, findall, sub, and groups;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.
Before any new tool — with what you already know: loops, split, slicing, string methods.
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.
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.
Another question, solved the hard way for you: “an a, then a b somewhere after it”. Predict the four lines:
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 |
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?
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:
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.
|| 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:
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.
*: 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:
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
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 |
Zero repetitions means x* also matches the empty text. mark shows an empty match as []. Predict:
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 → [].
check("(ab)*c", ["abbc"]) says no: the whole text does not fit. But mark looks inside the text. Predict:
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.
The same symbols, on texts you might really search. Predict where the brackets go:
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.
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.
Predict each line, then click:
(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.
| 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)*.
+ 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:
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.
{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:
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 textPredict where the brackets go:
[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?.
Only the symbols so far: |, *, +, ?, {m,n} and brackets. Write the pattern, then click.
Problem: mark every laugh — but not the lone h.
ha, one or more times: the brackets make ha one thing for the +. ha+ would mean haaaa.
Problem: mark every ciao, however long — but not cia.
Problem: mark only the long thinking noises: h and at least three m.
Problem: mark every title — whole.
.. matches exactly one character, whatever it is: letter, digit, space, punctuation — anything but a newline. Predict:
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:
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 >.
* and + take as much as they can. Add a ? after them — *?, +? — and they take as little as they can. Predict the four lines:
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.
[...]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:
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
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 |
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.
Predict where the brackets go:
[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.
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:
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.
^ 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:
[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.
\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:
[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.
| 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.
re functionsre.searchre.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:
<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:
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.
A match object is an object like those of Lecture 8: it has methods.
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 textsearch is happy with a match anywhere inside. re.fullmatch asks whether the whole text fits — the question check has been asking all along. Predict:
<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 matchfindall returns a list of every match, left to right, without overlaps. No match: an empty list (search gave None). Predict the last two lines:
['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.
Patterns are case-sensitive, like ==. Either lower the text first, or tell re to ignore case with a flag:
['alice']
['alice', 'alice', 'alice']
['Alice', 'alice', 'ALICE']
re.sub: replace every matchre.sub(pattern, replacement, text) returns a new string in which every match is replaced — strings never change (Lecture 3). Predict:
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.
Brackets do a second job: they capture the part they enclose. The match object gives it back with group(1), group(2), …
16/12/2026
16 12 2026
('16', '12', '2026')
sing
findall with groupsWith groups in the pattern, findall returns what the groups captured instead of the whole match:
['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 ....
Counter, a reminderFrom Lecture 7: Counter, from the module collections, counts the items of a list — the quickest way to count the words of a whole book.
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 |
Book, on the whole bookBook 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?
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.
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.
The whole book as one string, then one pattern per question:
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.
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()}")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.
|, star * — plus shortcuts: + ? {m,n}, ., [...], \d \w \s, \b ^ $.* + ? {m,n} repeat the one thing just before them; ( ) makes a piece one thing. * allows zero, and is greedy; *? is lazy.r"..."; \. for a literal dot.re.search → match object or None; re.fullmatch → the whole text; re.findall → list of every match; re.sub → a new string.( ) capture: m.group(1); findall returns groups, or tuples of groups. Check for None before you ask a match for its group().Problem: list every email address in text — and not @nobody.
Problem: how much is the bill? Find every price, then add them up.
Problem: list the hashtags, then the people mentioned — two lists.
Problem: remove the stage directions in brackets — keep only what is said.
Problem: for each line, print the subject and its reaction time as a number — or 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.
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 |
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
(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.
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.
Two of the results look like “no match” at first sight. Which, and why are they matches?
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.
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?
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).
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.
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 à.
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.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().
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.
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.
# 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.
(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.
Intro to Programming (Python) · Fall 2026