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
The built-in methods that clean and split text.
Describing a shape of text and finding every match.
Extracting fields and applying patterns across a whole column.
Real data contains much text: names, addresses, codes. Cleaning it is often the largest part of a project.
Extract every phone number from a block of irregular text.
A built-in action that a piece of text can perform, written after a dot.
e.g. " hi ".strip() gives back "hi"
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"
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"
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']
A set of allowed characters that fills one position in the text.
e.g. [A-Z] = one capital letter; \d = one digit
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
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
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"
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
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+"
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.
Sufficient for tidy, predictable text.
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.
Mathematician Stephen Kleene describes “regular events” in his own notation.
Ken Thompson builds them into a text editor to search text.
Thompson’s search tool, named after the editor command g/re/p.
A library copying Perl’s syntax; many modern tools use it.
Python’s re module uses the same Perl-style syntax, so a pattern written this week also works in many editors and languages.
g/re/p means: globally search for a regular expression and print the matching lines.
In the standard library of Java and Python, and built into JavaScript and Perl.
Google Sheets’ REGEXMATCH, REGEXEXTRACT and REGEXREPLACE take the same patterns.
Still the standard text search on every Mac and Linux machine.
The pattern language learned this week is one of the most portable skills in the course.
SourceWikipedia: Regular expression; Google Docs Editors Help: REGEXMATCH
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.
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.
pd.__version__the installed pandas: 3.0.5 on the laptop, 2.2.0 in the browsert.dtypeseach column’s type: str on the laptop, object in the browserStandard 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.
strip removes surrounding whitespace, lower normalises
case so comparisons work, and replace swaps out unwanted pieces.
text.lower() (week 4)"Cebu" and "CEBU" compare equals.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 "store the text, with two spaces at each end, in a variable called ss.strip()a new string with the spaces at both ends removed; s itself is unchangeds.strip().lower()chaining: strip first, then make the result lowercases.replace("City", "")swap every "City" for an empty string; the spaces around it stay, so the result still has spaces at both endsThe text this week is the description column of the 34,079 flood projects: free text typed by many people over ten years.
pd.read_csv(url)?pandas downloads with urllib, which this site’s bot protection answers with 403 Forbidden. requests gets through.
d = df.descriptiona short name for the text column, used on the next slides(34079, 15) 034,079 projects; no description is missingEvery flood control project has a description. They are inconsistent and abbreviated, and contain the kind of structure regex is designed for.
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.)
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 keywordsd.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 somewheresplit and joinThese 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.
"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| Method | Does | Example → 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 s | test containment | "bu" in "Cebu" → True |
These handle predictable text (True/False answers are
booleans, week 2). When the target has a shape but not a fixed value, the tool is a regular expression (regex): a short code that describes that shape.
"Any 11-digit number starting 09" is a pattern, which string methods cannot express.
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.
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.
"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 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 survivesre.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 fitsre.findall(pattern, text)find every match → a list of strings, ['3', '4']; an empty list [] if noneSearching for CONSTRUCTION also matches it inside RECONSTRUCTION — which is different work, silently added to the total.
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.
_ — what \w matches\b\b matches a position, so it uses up none"CONSTRUCTION"plain letters: found anywhere, including inside RECONSTRUCTIONr"\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 here393descriptions counted only because they say RECONSTRUCTION| Token | Matches | Used when |
|---|---|---|
^ | Start of the string | The pattern must begin the field |
$ | End of the string | Validating a whole value — e.g. the contract-ID pattern |
\b | A word boundary | Counting a keyword without catching it inside longer words |
(?=...) | A lookahead | Requiring something follows without consuming it |
Anchoring both ends with ^ and $ turns "contains something like this" into "is exactly this shape": the difference between finding and validating. Example: ^09 matches 09171234567 but not tel:09171234567.
(?=...): "only if this comes next", without including it in the match| Token | Matches | Token | Matches |
|---|---|---|---|
\d | a digit 0–9 | + | one or more |
\w | letter, digit, _ | * | zero or more |
. | any character | {4} | exactly four |
[A-Z] | one in the set | ^ $ | start / end |
A token (one building block) such as \d, or a
character class such as [A-Z] (a set of allowed characters
filling one position), says what. A quantifier
(+, *, {4}) says how many of the item immediately before it. Combined, they can describe almost any field.
r prefixPatterns are written as r"..." so \d stays literal.
In a normal string a backslash starts an escape: "\n" is a
line break and "\b" is a backspace. A raw string
r"..." passes every backslash to the regex untouched.
All contract IDs have 8 characters. This is the most common regex failure.
From the first few IDs (22F00136) the structure appears obvious: two digits, a letter or two, then five digits.
The pattern matches the test cases because it was validated only against the few rows that were inspected.
^ … $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%In the Shape column, D stands for any digit and L for any letter. All 34,079 are eight characters, but the split between letters and digits varies. The pattern demanding exactly five trailing digits matched only the minority, which happened to be the format of the first rows.
cid.apply(lambda s: ''.join('D' if c.isdigit() else 'L' for c in s)) then .value_counts(). Shapes, not guesses.
In words: for each ID (cid = the contract-ID column), write D for every digit and L for everything else, then count how many IDs share each shape. lambda s: … is a one-line, unnamed function.
+ 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%.
The fraction matched is always printed. An extraction that silently returns NaN is the central problem.
(\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 fit1.0the fraction of rows that matched: all of themsorted(ex[0].unique())the distinct year prefixes, in order: '14' … '26' = 2014–2026With the pattern working on all rows, the extracted year prefix can be checked against the year column. They agree 96.3% of the time.
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.
"20" + ex[0]+ on text glues it: "20" + "22" → "2022", for every row at oncedf.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,079df[... != ...]keep only the rows where the two years disagree (a True/False mask, week 6)len(bad)how many rows that is: 1,266Read left to right: a literal 09 (characters that mean themselves), then a digit, repeated nine times. This describes an 11-digit Philippine mobile number.
A pattern is written piece by piece, and each addition is tested on real samples.
What does
re.findall(r"\d{4}", "1998 and 2020") return?
['1', '9', '9', '8', ...]['1998', '2020']['19982020'][]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.
{4} groups four digits into one match. The quantifier changes the
whole result.
\d{4} = a four-digit chunk.
Next: extracting fields and applying patterns to a whole column.
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.
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.
(\d{4})-(\d{2})group 1: four digits; then a literal hyphen; then group 2: two digitsm = re.search(...)m is the match object: the text found plus what each group caughtm.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')* 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.
This is the character that broke the encoding in week 9. Real text repeatedly presents the same problems.
" (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.
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 ")"search returns the first match. findall returns every one, and with a lazy quantifier it returns the brackets individually.
.str.extractall() is the vectorised version, returning a row per match with a MultiIndex.
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| Target | Pattern | Read as | Matches |
|---|---|---|---|
| A 4-digit year | \d{4} | exactly four digits | 2024 |
| A PH mobile | 09\d{9} | "09", then exactly nine digits | 09171234567 |
| A date | \d{4}-\d{2}-\d{2} | 4 digits, hyphen, 2 digits, hyphen, 2 digits | 2024-08-31 |
| A word | \w+ | one or more word characters (letters, digits, _) | Cebu |
Recognition matters more than memorisation. A reference sheet, adapted to the actual data, is sufficient.
A site like regex101 shows, live, what each part of a pattern matches.
.str applies a pattern to every rowpandas 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.
.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 columnPatterns that look right often miss edge cases. They are checked against actual data.
If .startswith("09") is sufficient, regex is unnecessary.
A dense pattern becomes unreadable within a month; a comment states what it matches.
A regex is code. It requires the same clarity and testing as the functions written in Week 4.
The simplest tool that works is preferred; regex is reserved for cases that require a pattern.
Free text written by thousands of people cannot be captured by one pattern. The goal is not 100% but a known and reported coverage.
Sufficient to describe where most work takes place; insufficient for a complete geographic breakdown. The report states which claim is made.
d.str.extract(pattern, expand=False)the place name from every description; expand=False returns one column (a Series), not a tableplaces.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| Piece | Read as |
|---|---|
\b | at 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 "(" |
On "CONSTRUCTION OF FLOOD CONTROL STRUCTURE ALONG AGNO RIVER, BRGY. POBLACION" group 1 is 'AGNO RIVER': ALONG, a space, then capitals and spaces up to the comma.
Descriptions that name a place without ALONG or IN, or that end the name some other way, are not caught. This is acceptable, provided it is reported.
12,400 rows: the numerator of any subsequent claim.
36.4%. Without this, a reader assumes everything was extracted.
Ten non-matching rows are printed. They show whether the gap is random or systematic; systematic misses bias the result.
An extraction that covers a third of the data, reported as though it covered all of it, is the same failure as an unnoticed dropna() (which throws away rows with blanks, week 1) : a silent change to which rows the conclusion describes.
Regex is for shapes of text. When the structure is already known, something else parses it better and more safely.
HTML and JSON are not parsed with regex. Both nest arbitrarily; a regular expression fundamentally cannot track nesting.
->not Python: read as "use this instead"pd.read_html, json.loadsthe parsers from week 9 for HTML tables and JSON textThe common advice is "compile for performance". Measured over 34,079 strings, the gain is 1.16× — because the re module already caches recent patterns.
A named object that can be reused, passed around and tested. And flags attach once rather than at every call site.
re.compile(pat) turns pattern text into a ready-to-use pattern object, oncere automatically keeps recently used patterns so it need not redo themrx = re.compile(pat)turn the pattern into an object once, then call its .searchtime_ms(plain), time_ms(compiled)34,079 searches each way, timed with week 5’s helper1.16xa small gain: re already caches recent patterns, so the reason to compile is a readable name| Token | Means | Example |
|---|---|---|
\d \w \s | digit / 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 quantifier | make it lazy | (.*?) vs (.*) |
( ) | capture a group | (?P<yr>\d{2}) |
^ $ \b | positions, not characters | \bCONSTRUCTION\b |
| | alternation | (CONST|REHAB) |
\ | escape a special character | \( for a literal bracket |
Every pattern in this session is built from these. A need for more usually indicates that the text has structure a parser should handle instead.
| means "or": CONST|REHAB matches either word(?P<yr>...): a group with a name instead of a number.str.strip(), .str.upper(), re.sub(r"\s+", " ", s) (every run of whitespace becomes one space). Most "regex problems" are inconsistent whitespace and case.
Word boundaries for counting, anchors for validating, lazy quantifiers when there is more than one match per row.
notna().mean(), then ten non-matching rows are read, every time. This step is often skipped.
Step 3 distinguishes this from guessing. An extraction is a claim about the data, and like every other claim in this course it needs its denominator (the total used as the divisor: all 34,079 rows) stated.
Run the rigid contract-ID pattern. Confirm the result is 9.7% and that no error is raised.
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.
Loosen the quantifiers until notna().mean() is 1.0.
Pull the work type (CONSTRUCTION / REHABILITATION / …) from the description. Report the coverage, and inspect ten rows that did not match.
Step 4 contains the main lesson: a first pattern usually covers less than expected, and the misses are not random.
A .str.extract() call runs without error and the new column is 90% NaN. What happened?
expand=True is requiredstr.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.On "OCAÑA RIVER (GABIONS) (UPSTREAM)", what does re.search(r"\((.*)\)", t) capture?
"GABIONS""GABIONS) (UPSTREAM" — greedy matching runs to the last closing bracket["GABIONS", "UPSTREAM"].* 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.One pattern and one call extract every Philippine mobile number, regardless of the surrounding words. This is the intended use of regex.
, 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}.
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 skippedAnything that can be found can be replaced. Collapsing whitespace is the most frequent use, because real text contains many stray runs of it.
\s+ squeezes internal runs but leaves the single leading and trailing space it produced.
\1 in the replacement means "whatever group 1 caught".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.
re.sub(pattern, new, text)find every match and swap in new → a new stringr"\s+" → " "each run of spaces becomes a single space; .strip() then trims the endsr"\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(?P<name>...) turns a positional capture into a named one, and in pandas the names become column names.
ex[0], ex[1], ex[2] is unreadable a week later. ex.yr is not.
(?P<yr>\d{2})a group named yr that catches two digits; ?P<name> is the syntax that attaches the namelist(ex.columns)the new columns are called after the groups, not 0, 1, 2ex.head(3)the first three IDs, split into their three partsA 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.
.str.contains(..., case=False) is equivalent to re.IGNORECASE, and reads better in a chain.
re.IGNORECASEmatch letters in either case: cebu finds CEBUre.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 IDIn a regex, what does \d match?
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.
\d digit, \w word char, . anything. These three are learned first.
\d = one digit.
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.
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 ^…$).
Write one pattern that accepts both 0917... and +63917... formats.
strip/lower/replace and split/join for tidy text.
\d \w . + * {n} [ ] describe a pattern; findall retrieves matches.
Capturing with ( ); applying to columns with .str.
In summary: string methods clean text; when a shape rather than an exact value is required, regex describes it.
Extract structured values out of unstructured text.
s.strip()09\d{9}[A-Z], \d, \w, \s+ * ? {4} {1,2}( ) that capture part of a match^ start, $ end, \b word edge\( is a real bracketr"…": Python leaves backslashes alone; used for every patternsplit cuts at09re.search returns; read it with .group()\b, the edge where a word starts or ends.* takes as much as possible; .*? as little| means "or"\1: whatever group 1 caughtre.IGNORECASEComplete and submit the Week 10 lab. Practise writing \d{4} and re.findall without notes.
Python "Regular Expression HOWTO" — docs.python.org/3/howto/regex.
All materials are linked on the course page beside this deck.
Making a whole project reproducible: Git, environments, and debugging.
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