DS 208 · Week 10

Text Processing & Regular Expressions

Cleaning, searching, and extracting from irregular text with Python's string tools and the pattern language called regex.

Programming for Data Science · University of the Philippines Cebu

Outline

From string cleaning to pattern matching

Key terms

Ten terms used this week

string method

A built-in action that a piece of text can perform, written after a dot.

e.g. " hi ".strip() gives back "hi"

regular expression (regex)

A short code that describes a shape of text, so Python can find every piece that fits.

e.g. \d{4} means "four digits in a row"

pattern

The shape being searched for, written in regex. Most characters mean themselves; a few are special.

e.g. 09\d{9} = "09, then nine more digits"

match

A stretch of text that fits the pattern. re.search finds the first; re.findall finds them all.

e.g. re.findall(r"\d+", "3 cats 4 dogs") gives ['3', '4']

character class

A set of allowed characters that fills one position in the text.

e.g. [A-Z] = one capital letter; \d = one digit

quantifier

A symbol that says how many times the item immediately before it may repeat.

e.g. {4} exactly four · + one or more · * zero or more

group

Round brackets around part of a pattern; the text inside is kept ("captured") so it can be extracted.

e.g. (\d{4})-(\d{2}) on 2024-08 keeps 2024 and 08

anchor

A symbol that matches a position, not a character: ^ start, $ end, \b edge of a word.

e.g. ^09 = "the text must begin with 09"

escape

A backslash \ in front of a character flips its meaning between special and ordinary.

e.g. \( = a real bracket; \d = any digit, not the letter d

raw string

A string written r"…": Python leaves every backslash alone, so the regex gets it untouched.

e.g. always write patterns as r"\d+", never "\d+"

Previous session

Loaded data is rarely clean

Whatever the source, text arrives with stray spaces, mixed case, and values embedded in sentences. It must be cleaned and extracted before analysis.

A string is text in quotes (week 2), and a pandas column is a Series of values (week 6). This session adds the tools that clean and search the text inside them.

String methods

Sufficient for tidy, predictable text.

Regex

For cases that require a pattern, not an exact string.

String methods resemble Find & Replace in Word, which needs the exact text, whereas regex resembles a request to "find every 11-digit number that starts with 09", which describes what the text looks like, not what it is.

About the tool

Regular expressions began as mathematics

1951

Kleene

Mathematician Stephen Kleene describes “regular events” in his own notation.

1968

QED

Ken Thompson builds them into a text editor to search text.

1973

grep

Thompson’s search tool, named after the editor command g/re/p.

1997

PCRE

A library copying Perl’s syntax; many modern tools use it.

SourceWikipedia: Regular expression; Wikipedia: grep

About the tool

Where regular expressions are used

SourceWikipedia: Regular expression; Google Docs Editors Help: REGEXMATCH

Runnable code

Patterns on these slides run in the browser

As in earlier weeks, a block with a ▶ Run / Edit button runs in the browser and can be changed. Regular expressions are ideal for this: change one character of a pattern, run it again, and see what it matches now.

What does not run here

The flood descriptions cannot be downloaded in the browser, so the blocks that search all 34,079 have no button; the companion notebook runs them.

import io, sys print("pandas version:", pd.__version__) print("64-bit Python:", sys.maxsize > 2**32) t = pd.read_csv(io.StringIO("city,pop\nCebu,964000")) print(t.dtypes) pandas version: 3.0.5 64-bit Python: True city str pop int64 dtype: object
  • pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browser
  • t.dtypeseach column’s type: str on the laptop, object in the browser
Part A

String methods

Standard tools for cleaning text.

Text is stored in strings. This part adds string methods (built-in actions a string performs on itself) to trim, re-case, swap and split it.

Exercise · 3 min

Three methods for cleaning text

strip removes surrounding whitespace, lower normalises case so comparisons work, and replace swaps out unwanted pieces.

Key terms

method
a function that belongs to a value, called with a dot: text.lower() (week 4)
whitespace
the invisible characters: spaces, tabs and line breaks
normalise
make every value follow the same rules, so "Cebu" and "CEBU" compare equal

Tasks

  1. Predict the three printed strings, spaces included.
  2. Select ▶ Run / Edit and run the code.
  3. Change the last line to s.strip().replace(" City", ""). What prints now?

Result on the lecture laptop (select to reveal)

'Cebu City', 'cebu city' and ' Cebu ': replace removed the word but kept every space around it. Stripping first and replacing " City" (with its space) gives 'Cebu'.

s = " Cebu City " print(repr(s.strip())) print(repr(s.strip().lower())) print(repr(s.replace("City", "")))
  • s = " Cebu City "store the text, with two spaces at each end, in a variable called s
  • s.strip()a new string with the spaces at both ends removed; s itself is unchanged
  • s.strip().lower()chaining: strip first, then make the result lowercase
  • s.replace("City", "")swap every "City" for an empty string; the spaces around it stay, so the result still has spaces at both ends
Case study

The flood descriptions, loaded from the course API

The text this week is the description column of the 34,079 flood projects: free text typed by many people over ten years.

Why not pd.read_csv(url)?

pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.

import io, requests url = "https://portal.latarak.com/api/flood/export.csv" df = pd.read_csv(io.StringIO(requests.get(url, timeout=60).text)) d = df.description # 34,079 descriptions, written by many people print(df.shape, d.isna().sum()) (34079, 15) 0
  • d = df.descriptiona short name for the text column, used on the next slides
  • (34079, 15) 034,079 projects; no description is missing
34,079 real descriptions

Free text written by many authors

Every flood control project has a description. They are inconsistent and abbreviated, and contain the kind of structure regex is designed for.

Counting before extracting

str.contains answers most questions and cannot fail silently as extraction can. (Extracting = copying the matched piece out into its own column; later slides show it silently missing rows.)

for kw in ["CONSTRUCTION", "REHABILITATION", "IMPROVEMENT", "REPAIR"]: print(kw, d.str.contains(kw, na=False).sum()) CONSTRUCTION 26552 REHABILITATION 6387 IMPROVEMENT 2791 REPAIR 1010
  • d = df.descriptiondf is the flood-control projects DataFrame from weeks 5–9; d is its description column (34,079 texts)
  • for kw in [...]:run the indented line once for each of the four keywords
  • d.str.contains(kw, na=False).str applies a string method to every row → one True/False per row; na=False counts a missing description as False
  • .sum()adds up the Trues (True counts as 1)
  • CONSTRUCTION 26,55226,552 descriptions contain the letters CONSTRUCTION somewhere
Text ↔ list

split and join

These two are inverses (each undoes the other). split turns one string into a list on a separator — the character that marks where to cut; join combines a list back into one string.

print("Cebu,Davao,Iloilo".split(",")) print(", ".join(["a", "b", "c"])) ['Cebu', 'Davao', 'Iloilo'] a, b, c
  • "Cebu,Davao,Iloilo".split(",")cut the text at every comma; the commas are thrown away
  • ['Cebu', 'Davao', 'Iloilo']square brackets = a list (week 3) of three strings, each in quotes
  • ", ".join([...])the string before the dot is the separator: put ", " between the items
  • "a, b, c"one single string again
Reference

Common string methods

MethodDoesExample → result
.strip()trim whitespace" hi ".strip() → "hi"
.lower()lowercase"HI".lower() → "hi"
.replace(a, b)swap text"a-b".replace("-","_") → "a_b"
.startswith(x)test the start"09xx".startswith("09") → True
x in stest containment"bu" in "Cebu" → True
Part B

Regular expressions

Describing a shape and finding every match.

Part A cleaned text whose exact value is known. This part adds regex: a way to describe text by its shape ("four digits", "starts with 09") and find every piece that fits.

Exercise · 3 min

Searching for a shape of text

A regex is a mini-language for describing patterns: "four digits," "a word," "starts with 09." search finds the first; findall returns them all.

The description itself is the pattern; each stretch of text that fits it is a match.

A regex is a wanted poster that describes rather than names ("all digits, one or more of them"), and Python checks every stretch of the text against it.

Tasks

  1. Predict both printed results.
  2. Select ▶ Run / Edit and run the code.
  3. Change the text to "12 cats 4 dogs" and the pattern to r"\d". What does findall return?

Result on the lecture laptop (select to reveal)

42 and ['3', '4']. With r"\d" each digit is its own match: ['1', '2', '4']; with \d+ it would be ['12', '4'], because + means “one or more”.

import re m = re.search(r"\d+", "order 42") print(m.group()) print(re.findall(r"\d+", "3 cats 4 dogs"))
  • import reload re, Python's built-in regex module (a toolbox that ships with Python)
  • r"\d+"the pattern. \d = one digit, + = one or more of it → "a run of digits". The r makes it a raw string, so the backslash survives
  • re.search(pattern, text)find the first match. Python shows <re.Match object; span=(6, 8), match='42'>: a match object, found at positions 6–8; None if nothing fits
  • re.findall(pattern, text)find every match → a list of strings, ['3', '4']; an empty list [] if none
Word boundaries

A plain keyword count overstates by 393

Searching for CONSTRUCTION also matches it inside RECONSTRUCTION — which is different work, silently added to the total.

\b is a zero-width assertion

An assertion is a check, not a character: it matches the position between a word character and a non-word one. It consumes nothing, so it does not change what is captured.

Key terms

word character
a letter, digit or underscore _ — what \w matches
word boundary \b
the invisible edge where a word starts or ends
zero-width / consume
a token "consumes" the characters it matches; \b matches a position, so it uses up none
# substring: also catches RECONSTRUCTION print(d.str.contains("CONSTRUCTION", na=False).sum()) # word boundary: the real count print(d.str.contains(r"\bCONSTRUCTION\b", na=False).sum()) 26552 26159
  • "CONSTRUCTION"plain letters: found anywhere, including inside RECONSTRUCTION
  • r"\bCONSTRUCTION\b"read as: word edge, the letters CONSTRUCTION, word edge. In RECONSTRUCTION the "RE" sits before it, so there is no edge → no match
  • .str.contains(...)treats its text as a regex by default, so \b works here
  • 393descriptions counted only because they say RECONSTRUCTION
Anchors and boundaries

Four tokens that match a position, not a character

TokenMatchesUsed when
^Start of the stringThe pattern must begin the field
$End of the stringValidating a whole value — e.g. the contract-ID pattern
\bA word boundaryCounting a keyword without catching it inside longer words
(?=...)A lookaheadRequiring something follows without consuming it
Regex tokens

Seven basic tokens

TokenMatchesTokenMatches
\da digit 0–9+one or more
\wletter, digit, _*zero or more
.any character{4}exactly four
[A-Z]one in the set^ $start / end
A plausible pattern

A pattern that matches 9.7% of the data

All contract IDs have 8 characters. This is the most common regex failure.

Building from visible examples

Error: a pattern built from the first rows

From the first few IDs (22F00136) the structure appears obvious: two digits, a letter or two, then five digits.

Common error

The pattern matches the test cases because it was validated only against the few rows that were inspected.

pat = r"^(\d{2})([A-Z]{1,2})(\d{5})$" ex = df.contract_id.str.extract(pat) print(ex[0].notna().sum()) print(round(ex[0].notna().mean(), 3)) # and NOT ONE error was raised 3311 0.097
  • ^ … $anchors: the whole ID, start to end, must fit
  • (\d{2})group 1: exactly two digits (22)
  • ([A-Z]{1,2})group 2: one or two capital letters (F)
  • (\d{5})group 3: exactly five digits (00136)
  • .str.extract(pat)run the pattern on every ID; each group becomes a column 0, 1, 2; a row that does not match gets NaN (missing, week 6)
  • ex[0].notna().sum() / .mean()how many / what fraction of rows are not missing → 3,311 rows, 0.097 = 9.7%
Shape analysis

Two formats; the rigid pattern excludes the larger one

shape projects rigid {5} flexible + LLLLLLLL e.g. 22F00136 34,079 (100.0%) matches matches D = a digit, L = a letter. All IDs are 8 characters; only the split differs.
Correction

Flexible quantifiers for variable parts

+ means "one or more". Using it where the length genuinely varies, and exact counts only where it does not, takes this from 9.7% to 100%.

Verifying coverage

The fraction matched is always printed. An extraction that silently returns NaN is the central problem.

pat = r"^(\d{2})([A-Z]+)(\d+)$" ex = df.contract_id.str.extract(pat) print(ex[0].notna().mean()) # the year prefix decodes too years = sorted(ex[0].unique()) print(years[:3], "...", years[-2:]) 1.0 ['14', '15', '16'] ... ['25', '26']
  • (\d{2})still exact: every ID starts with exactly two year digits
  • ([A-Z]+)one or more capital letters: F and BI both fit
  • (\d+)one or more digits: four or five both fit
  • 1.0the fraction of rows that matched: all of them
  • sorted(ex[0].unique())the distinct year prefixes, in order: '14' … '26' = 2014–2026
Result

1,266 IDs disagree with their year column

With the pattern working on all rows, the extracted year prefix can be checked against the year column. They agree 96.3% of the time.

3.7% is a real inconsistency

Not a regex bug — a data one. Contract 20BH0131 carries a 2020 prefix on a row labelled 2019. Any analysis using either field should note this.

# ex: the decoded IDs from the previous slide prefix_year = "20" + ex[0] bad = df[prefix_year != df.year.astype(str)] print(len(bad), round(len(bad) / len(df), 3)) print(bad[["contract_id", "year"]].head(3)) 1266 0.037 contract_id year 325 20BH0131 2019 856 22MF0066 2021 1720 20CH0073 2019
  • "20" + ex[0]+ on text glues it: "20" + "22" → "2022", for every row at once
  • df.year.astype(str)the year column holds numbers (int64); convert them to text so we compare like with like. Without it every row differs: 34,079
  • df[... != ...]keep only the rows where the two years disagree (a True/False mask, week 6)
  • len(bad)how many rows that is: 1,266
Reading a pattern

Structure of a PH mobile number pattern

09\d{9} literal "09" every PH mobile starts here \d — a digit any single 0–9 {9} — nine times so 2 + 9 = 11 digits total
Review question

Question (select to reveal the answer)

What does re.findall(r"\d{4}", "1998 and 2020") return?

A · ['1', '9', '9', '8', ...]
B · ['1998', '2020']
C · ['19982020']
D · []

B — ['1998', '2020'].

\d{4} means "exactly four digits in a row," so it matches each four-digit run as one match. \d alone would give answer A.

Break

  Five minutes

Next: extracting fields and applying patterns to a whole column.

Part C

Regex in practice

Extracting fields and cleaning whole columns.

Part B covered writing a pattern and finding its matches. This part adds groups, which extract only the required pieces, and applies patterns to a whole pandas column.

Worked example

Parentheses capture parts of a match

Wrapping part of a pattern in ( ) captures it: that bracketed part is a group. After a match, .group(1), .group(2) return each captured piece separately.

Highlighting parts of a found sentence, where the whole match is found but only the highlighted parts are copied out.

import re m = re.search(r"(\d{4})-(\d{2})", "2024-08") print(m.group(1)) # the year print(m.group(2)) # the month 2024 08
  • (\d{4})-(\d{2})group 1: four digits; then a literal hyphen; then group 2: two digits
  • m = re.search(...)m is the match object: the text found plus what each group caught
  • m.group(1)the text group 1 caught → '2024'. m.group(0) is the whole match, '2024-08'
  • m.groups()every group at once, as a tuple: ('2024', '08')
Exercise · 3 min

Greedy and lazy matching on two bracket pairs

* and + are greedy: they take as much as they can while still allowing a match. With two sets of brackets, this gives the wrong result. Adding ? makes them lazy: as little as possible.

A Cebu project, with a ñ

This is the character that broke the encoding in week 9. Real text repeatedly presents the same problems.

Tasks

  1. Predict what each of the two patterns returns.
  2. Select ▶ Run / Edit and run the code.
  3. Add " (PHASE II)" to the end of t. What does the greedy pattern return now?

Result on the lecture laptop (select to reveal)

Greedy: GABIONS) (UPSTREAM, everything from the first ( to the last ); lazy: GABIONS. With a third bracket the greedy match grows to GABIONS) (UPSTREAM), CARCAR CITY, CEBU (PHASE II; the lazy one is unchanged. 1,543 flood descriptions have two or more brackets.

import re t = "CONSTRUCTION OF OCAÑA RIVER (GABIONS) (UPSTREAM), CARCAR CITY, CEBU" # greedy: runs to the LAST ) print(re.search(r"\((.*)\)", t).group(1)) # lazy: stops at the FIRST ) print(re.search(r"\((.*?)\)", t).group(1))
  • tthe description text shown in the two comment lines
  • \( and \)escaped: a real "(" and ")" in the text, not a group
  • (.*)group: . any character, * zero or more, as many as possible → runs to the last ")"
  • (.*?)the extra ? = as few as possible → stops at the first ")"
Worked example

Retrieving every match with findall

search returns the first match. findall returns every one, and with a lazy quantifier it returns the brackets individually.

In pandas: extractall

.str.extractall() is the vectorised version, returning a row per match with a MultiIndex.

Key terms

vectorised
runs on the whole column in one call, with no explicit loop (week 5)
MultiIndex
row labels with two parts, here (original row, match number 0, 1, …)
import re t = "CONSTRUCTION OF OCAÑA RIVER (GABIONS) (UPSTREAM), CARCAR CITY, CEBU" print(re.findall(r"\((.*?)\)", t)) # a whole column: one row per match s = pd.Series([t, "DIKE (PHASE II)"]) print(s.str.extractall(r"\((.*?)\)")) ['GABIONS', 'UPSTREAM'] 0 match 0 0 GABIONS 1 UPSTREAM 1 0 PHASE II
  • re.findall(r"\((.*?)\)", t)every lazy match in one string, as a list
  • .str.extractall(…)the same for a whole column: one row per match, indexed by (row, match number)
  • .str.extract(…)by contrast, takes only the FIRST match in each row
Reference

Frequently used patterns

TargetPatternRead asMatches
A 4-digit year\d{4}exactly four digits2024
A PH mobile09\d{9}"09", then exactly nine digits09171234567
A date\d{4}-\d{2}-\d{2}4 digits, hyphen, 2 digits, hyphen, 2 digits2024-08-31
A word\w+one or more word characters (letters, digits, _)Cebu
Whole columns

.str applies a pattern to every row

pandas provides string and regex tools through .str. contains filters; extract pulls a captured group into a new column, vectorized (the whole column in one call) with no loop.

contacts = pd.DataFrame({ "name": ["Ana", "Ben", "Cris"], "phone": ["09171234567", "0917-123", "09228889999"], "code": ["FC-2024-031", "FC-2023-118", "FC-2025-007"]}) valid = contacts["phone"].str.contains(r"^09\d{9}$") print(contacts[valid].name.tolist()) # rows with a valid mobile print(contacts["code"].str.extract(r"(\d{4})")) # the year, as a column ['Ana', 'Cris'] 0 0 2024 1 2023 2 2025
  • .str.contains(r"^09\d{9}$")True where the whole value is 09 and nine more digits
  • .str.extract(r"(\d{4})")the first four-digit run in each code, as a new column
Using regex appropriately

Limits on regex use

Partial extraction

A place-name pattern that matches 36%

Free text written by thousands of people cannot be captured by one pattern. The goal is not 100% but a known and reported coverage.

12,400 of 34,079

Sufficient to describe where most work takes place; insufficient for a complete geographic breakdown. The report states which claim is made.

places = d.str.extract( r"\b(?:ALONG|IN)\s+([A-Z][A-Z\s\.]{3,40}?)(?:,|\s+\()", expand=False) print(places.notna().sum(), round(places.notna().mean(), 3)) print(places.dropna().str.strip().value_counts().head(3)) 12400 0.364 description AGNO RIVER 140 ANGAT RIVER 131 RIO CHICO RIVER 105 Name: count, dtype: int64
  • d.str.extract(pattern, expand=False)the place name from every description; expand=False returns one column (a Series), not a table
  • places.notna().sum()12,400 rows matched; the other 21,679 are NaN
  • .value_counts().head(3)the three most common place names and how often each appears
Reading the code

The place-name pattern, piece by piece

PieceRead as
\bat the edge of a word
(?:ALONG|IN)the word ALONG or IN. | means "or"; (?: ) groups without capturing (nothing is kept)
\s+one or more whitespace characters
( … )group 1: the place name we keep
[A-Z]it starts with a capital letter
[A-Z\s\.]{3,40}?then 3 to 40 more capitals, spaces or dots (\. = a real dot); the ? = lazy, stop as early as possible
(?:,|\s+\()stop at a comma, or at spaces followed by a real "("
Reporting coverage

Three numbers with every extraction

When not to use regex

Three cases where regex is the wrong tool

Regex is for shapes of text. When the structure is already known, something else parses it better and more safely.

Common error

HTML and JSON are not parsed with regex. Both nest arbitrarily; a regular expression fundamentally cannot track nesting.

Key terms

parse / parser
read a known format into usable pieces; a parser is a tool built for one format
nesting
boxes inside boxes: a table inside a section inside a page
# NO — use a parser re.findall(r"<td>(.*?)</td>", html) -> pd.read_html(html) # NO — it is already structured re.search(r'"region": "(.*?)"', text) -> json.loads(text)["region"] # NO — a plain method is clearer re.search(r"^CONST", s) -> s.startswith("CONST")
  • ->not Python: read as "use this instead"
  • pd.read_html, json.loadsthe parsers from week 9 for HTML tables and JSON text
Compiling

Compiling for readability rather than speed

The common advice is "compile for performance". Measured over 34,079 strings, the gain is 1.16× — because the re module already caches recent patterns.

Reasons to compile

A named object that can be reused, passed around and tested. And flags attach once rather than at every call site.

Key terms

compile
re.compile(pat) turns pattern text into a ready-to-use pattern object, once
cache
a short memory: re automatically keeps recently used patterns so it need not redo them
ms
milliseconds, thousandths of a second
# time_ms(f) is week 5's timeit helper descriptions = df.description.tolist() pat = r"\bRIVER\b" def plain(): for s in descriptions: re.search(pat, s) rx = re.compile(pat) def compiled(): for s in descriptions: rx.search(s) a, b = time_ms(plain), time_ms(compiled) print(f"{a:.1f} ms, {b:.1f} ms, {a / b:.2f}x") 25.6 ms, 22.0 ms, 1.16x
  • rx = re.compile(pat)turn the pattern into an object once, then call its .search
  • time_ms(plain), time_ms(compiled)34,079 searches each way, timed with week 5’s helper
  • 1.16xa small gain: re already caches recent patterns, so the reason to compile is a readable name
Essential tokens

Ten tokens that cover most patterns

TokenMeansExample
\d \w \sdigit / word char / whitespace\d{2} → 22
[A-Z]any one of a set[A-Z]+ → BI
+ * ?one-or-more / zero-or-more / optional[A-Z]+
{n} {n,m}exactly n / between n and m\d{5}
.any character except newline(.*?)
? after a quantifiermake it lazy(.*?) vs (.*)
( )capture a group(?P<yr>\d{2})
^ $ \bpositions, not characters\bCONSTRUCTION\b
|alternation(CONST|REHAB)
\escape a special character\( for a literal bracket
Workflow

Clean, then extract, then verify

Exercise · 8 min

Diagnosing and correcting a pattern

1 · Reproduce the failure

Run the rigid contract-ID pattern. Confirm the result is 9.7% and that no error is raised.

2 · Diagnose with shapes

Map each ID to a D/L signature (D for a digit, L for a letter, as on the shapes slide) and value_counts() it. Identify the two formats.

3 · Fix and verify

Loosen the quantifiers until notna().mean() is 1.0.

4 · Extract something useful

Pull the work type (CONSTRUCTION / REHABILITATION / …) from the description. Report the coverage, and inspect ten rows that did not match.

Review question

Question (select to reveal the answer)

A .str.extract() call runs without error and the new column is 90% NaN. What happened?

A · The source column is 90% missing
B · The pattern did not match those rows — extract returns NaN rather than raising
C · expand=True is required
D · pandas silently dropped the rows
B. str.extract reports a non-match as NaN, so a pattern that fits only a minority of the data produces a mostly-empty column and no error. For this reason notna().mean() is checked after every extraction. Here the rigid contract-ID pattern matched 9.7% because it demanded exactly five trailing digits, and 90.3% of IDs have four.
Review question

Question (select to reveal the answer)

On "OCAÑA RIVER (GABIONS) (UPSTREAM)", what does re.search(r"\((.*)\)", t) capture?

A · "GABIONS"
B · "GABIONS) (UPSTREAM" — greedy matching runs to the last closing bracket
C · ["GABIONS", "UPSTREAM"]
D · Nothing — the brackets need escaping
B. .* is greedy: it takes as much as possible while still permitting a match, so it runs past the first ) to the last one. The lazy .*? stops at the first, and re.findall (or .str.extractall) returns every pair. 1,543 descriptions in this dataset contain two or more brackets.
Exercise · 3 min

Extracting every mobile number from a message

One pattern and one call extract every Philippine mobile number, regardless of the surrounding words. This is the intended use of regex.

Tasks

  1. Predict the list that prints.
  2. Select ▶ Run / Edit and run the code.
  3. Add , 0917 123 4567 (with spaces) to the text. Is it found?

Result on the lecture laptop (select to reveal)

['09171234567', '09228889999']. The spaced number is not found: \d{9} needs nine digits in a row. Allowing optional spaces would need 09\d{2}\s?\d{3}\s?\d{4}.

import re text = "Call 09171234567 or 09228889999" print(re.findall(r"09\d{9}", text))
  • 09literal: the characters 0 then 9
  • \d{9}exactly nine more digits (11 in total)
  • re.findall(...)every match, left to right, as a list; the words "Call" and "or" are skipped
Exercise · 3 min

Using patterns to rewrite text

Anything that can be found can be replaced. Collapsing whitespace is the most frequent use, because real text contains many stray runs of it.

Chain with .strip()

\s+ squeezes internal runs but leaves the single leading and trailing space it produced.

Key term

backreference
\1 in the replacement means "whatever group 1 caught"

Tasks

  1. Predict both cleaned strings.
  2. Select ▶ Run / Edit and run the code.
  3. Delete .strip() from the first line. What changes?

Result on the lecture laptop (select to reveal)

CONST. OF FLOOD CONTROL STRUCTURE, CEBU and STRUCTURE, CEBU. Without .strip(), one space is left at the end: \s+ squeezed the trailing spaces to one but could not remove it.

import re s = "CONST. OF FLOOD CONTROL STRUCTURE, CEBU " print(re.sub(r"\s+", " ", s).strip()) # reference a group with \1 print(re.sub(r"\s+([,.])", r"\1", "STRUCTURE , CEBU ."))
  • re.sub(pattern, new, text)find every match and swap in new → a new string
  • r"\s+" → " "each run of spaces becomes a single space; .strip() then trims the ends
  • r"\s+([,.])"spaces, then group 1: one comma or full stop (inside [ ] a dot is a literal dot)
  • r"\1"put back only the punctuation group 1 caught, so the spaces before it vanish
Named groups

Naming groups instead of numbering them

(?P<name>...) turns a positional capture into a named one, and in pandas the names become column names.

Useful beyond two groups

ex[0], ex[1], ex[2] is unreadable a week later. ex.yr is not.

pat = r"^(?P<yr>\d{2})(?P<office>[A-Z]+)(?P<seq>\d+)$" ex = df.contract_id.str.extract(pat) print(list(ex.columns)) print(ex.head(3)) ['yr', 'office', 'seq'] yr office seq 0 22 F 00136 1 18 BI 0029 2 19 CD 0029
  • (?P<yr>\d{2})a group named yr that catches two digits; ?P<name> is the syntax that attaches the name
  • list(ex.columns)the new columns are called after the groups, not 0, 1, 2
  • ex.head(3)the first three IDs, split into their three parts
Worked example

Flags that change the behaviour of a whole pattern

A flag is an on/off option for the whole pattern. Three are in common use. They are passed to re functions, or written inline as (?i) inside a pandas pattern.

case=False is the pandas shortcut

.str.contains(..., case=False) is equivalent to re.IGNORECASE, and reads better in a chain.

import re print(re.search(r"cebu", "CARCAR CITY, CEBU", re.IGNORECASE)) # VERBOSE: whitespace and comments inside the pattern rx = re.compile(r""" ^(\d{2}) # 2-digit year ([A-Z]+) # office code (\d+)$ # sequence """, re.VERBOSE) print(rx.match("22F00136").groups()) <re.Match object; span=(13, 17), match='CEBU'> ('22', 'F', '00136')
  • re.IGNORECASEmatch letters in either case: cebu finds CEBU
  • re.VERBOSEspaces and # comments inside the pattern are ignored, so it can be laid out and explained
  • .match(…).groups()the three captured parts of one contract ID
Review question

Question (select to reveal the answer)

In a regex, what does \d match?

A · any letter
B · a single digit 0–9
C · a space
D · the literal letter d

B — a single digit 0–9.

\d is one digit; a quantifier such as + or {4} matches more. \w is the one that also covers letters.

This week's lab

Cleaning text and extracting with regex

The lab cleans an irregular column with string methods, uses patterns to extract years and phone numbers, and applies one across a whole DataFrame column. About 45 minutes.

Lab tasks

strip/lower/split, re.findall, groups, and .str.extract.

Two new names: re.split cuts text wherever the pattern matches, and re.fullmatch succeeds only if the whole string fits (like wrapping the pattern in ^…$).

Optional extension

Write one pattern that accepts both 0917... and +63917... formats.

Summary

Cleaning text and matching shapes

Glossary

This week's terms, one line each

Key terms

string method
built-in action on text, after a dot: s.strip()
regular expression (regex)
a short code describing a shape of text
pattern
the shape searched for, e.g. 09\d{9}
match
a stretch of text that fits the pattern
character class
allowed characters for one position: [A-Z], \d, \w, \s
quantifier
how many of the thing before: + * ? {4} {1,2}
group
brackets ( ) that capture part of a match
anchor
matches a position: ^ start, $ end, \b word edge
escape
backslash that flips special/ordinary: \( is a real bracket
raw string
r"…": Python leaves backslashes alone; used for every pattern

Additional terms

whitespace
spaces, tabs and line breaks
separator
the character split cuts at
literal
a character that means itself, like 09
match object
what re.search returns; read it with .group()
word boundary
\b, the edge where a word starts or ends
greedy / lazy
.* takes as much as possible; .*? as little
alternation
| means "or"
backreference
\1: whatever group 1 caught
flag
an option for the whole pattern, e.g. re.IGNORECASE
compile
turn pattern text into a reusable pattern object
extract / coverage
copy matches into a column / the share of rows that matched
Preparation for next week

Practice & reading

Next Week

Reproducible workflows

Git for version history, virtual environments for pinned dependencies, and a systematic method of debugging, so that work runs identically for everyone.

DS 208 · Programming for Data Science