How do I find patterns in text with re?

Extract dates from file names with re.search and re.findall, capture a ticker and an ownership percentage with groups, and apply a pattern to every row of a pandas column.

After this lesson, you can read the dates in a file name, extract an ownership percentage from a cover page, and pick out the rows of a column that match a pattern.

How do I find the first date or every date?

A regular expression is a pattern that describes text, and re.search(r"\d{8}", file_name) returns the first run of eight digits, while re.findall returns every run. In AAA_20260302_20260306.csv, the first date is 20260302 and the two dates are 20260302 and 20260306.

\d matches one digit and {8} asks for eight in a row, and the r before the quotes keeps Python from reading the backslash itself. re.search returns a match object, whose .group(0) is the matched text, or None when nothing matches, while re.findall then returns an empty list. The pattern checks the spelling of a date, and a date such as 20261399 still passes. The made-up texts are two file names, two Kenneth French-style headings, a Schedule 13D cover line and three Shiller-style month labels.

The following box builds the texts and searches the first file name and the cover line.

import re

import pandas as pd

texts = pd.Series([
    "AAA_20260302_20260306.csv",
    "BBB_20260303.csv",
    "Average Value Weighted Returns",
    "  Average Equal Weighted Returns",
    "Percent of class (CCC): 7.5%",
    "2026.01",
    "2026.1",
    "Note for 2026.1",
])
print(re.search(r"\d{8}", texts[0]).group(0), re.findall(r"\d{8}", texts[0]))
print(re.search(r"\d{8}", texts[4]), re.findall(r"\d{8}", texts[4]))
20260302 ['20260302', '20260306']
None []

How do I capture the ticker and the percentage?

Parentheses in a pattern capture a piece of the match as a numbered group, so r"\(([A-Z]{3})\): (\d+\.\d+)%" captures the ticker as group 1, CCC, and the percentage as group 2, 7.5. Group 0 is the whole match.

[A-Z]{3} matches three capital letters, \( and \) match the printed parentheses, \d+ matches one or more digits and \. a period. The percent sign lies outside group 2, so the group holds only the number.

The following box captures both groups from the cover line.

match = re.search(r"\(([A-Z]{3})\): (\d+\.\d+)%", texts[4])
print(match.group(0), match.group(1), match.group(2))
(CCC): 7.5% CCC 7.5

How do I apply a pattern to every row of a column?

The .str methods of a pandas column apply a pattern to each row, .str.contains finds it anywhere, .str.fullmatch needs it to cover the whole text, and .str.extract returns a captured group. The month pattern r"\d{4}\.\d{1,2}" is found in all three month texts, but only 2026.01 and 2026.1 match whole, and the headings give the weighting Value and Equal.

{1,2} accepts one or two digits, so October written as 2026.1 passes, as in Shiller’s workbook. expand=False returns the group as one column, and a row without a match gets NaN. The pattern also accepts a month such as 19, so a check that the month lies between 1 and 12 belongs to the date conversion.

The following box tests the month texts and extracts the weighting from the headings.

month_texts = texts.loc[5:7]
print(pd.DataFrame({"text": month_texts, "contains": month_texts.str.contains(r"\d{4}\.\d{1,2}"), "fullmatch": month_texts.str.fullmatch(r"\d{4}\.\d{1,2}")}))
headings = texts.loc[2:4]
print(pd.DataFrame({"text": headings, "weighting": headings.str.extract(r"Average (Value|Equal) ", expand=False)}))
              text  contains  fullmatch
5          2026.01      True       True
6           2026.1      True       True
7  Note for 2026.1      True      False
                               text weighting
2    Average Value Weighted Returns     Value
3    Average Equal Weighted Returns     Equal
4      Percent of class (CCC): 7.5%       NaN

Your turn

Print the first eight-digit date of every text that starts with three capital letters and an underscore. You should see 20260302 for row 0 and 20260303 for row 1.

.str.match tests the start of each text.

file_names = texts[texts.str.match(r"[A-Z]{3}_")]
print(file_names.str.extract(r"(\d{8})", expand=False))
0    20260302
1    20260303
dtype: object