Lesson

Patterns in Text: Regular Expressions

Find numbers, identifiers, dates and codes inside the text of real arXiv pages with Python regular expressions: raw strings, re.search and re.findall, character classes, quantifiers, groups and the shortest match, and when Beautiful Soup is the better tool.

Last updated:


In this lesson we learn what a regular expression is, how the Python module re finds the pieces of a text that fit a pattern, how characters, repetitions and groups describe the pattern, and when a pattern is the right tool and when Beautiful Soup is.

Where is the number of pages?

Authors who post a paper on arXiv can add a line of comments, written as free text:
7 pages, 5 figures. Accepted to ASP-DAC 2027. We want the number of pages of every paper that says it, for example to see how long papers in Hardware Architecture are.
Beautiful Soup brings us to the element that holds the comment, as in From One Element to All Entries: find_all, Numbers and Missing Values.
The number inside the text has no element of its own: it is a piece of text with a shape, digits, a space and the word pages.

Text can be cut with split and replace, and that works while the number sits in a known place.
A regular expression describes the shape instead of the place:
the program asks for digits followed by the word, wherever they are in the text.
Anyone who collects text from the web meets this need: prices, dates, phone numbers, identifiers and sizes sit inside sentences.

The examples run in your browser: select Run from top to bottom, because the boxes of this page share their variables with each other.
If you press Stop or reload, run the page again from the top.
The first run of the page loads the libraries, so it can take a moment.

The notebooks of this lesson:

The first box requests the saved copy of the list of October 2026 and builds the soup, as in From a Web Page to Data: Beautiful Soup, so that this page stands on its own.
It then puts the text of the comment of every paper in the list comments.
Of the 25 papers, 12 have a line of comments.

import requests
from bs4 import BeautifulSoup

base_url = (
    'https://dvirross.com/materials/courses/'
    'intro-data-science/'
)
list_url = base_url + 'arxiv-cs-ar-2026-10.htm'
page_text = requests.get(list_url).text
soup = BeautifulSoup(page_text, 'html.parser')

boxes = soup.find_all('div', class_='list-comments')
comments = [
    box.text.replace('Comments:', '').strip()
    for box in boxes
]
print(len(comments))
print(comments[1])
12
7 pages, 5 figures. Accepted to ASP-DAC 2027

Cutting by place works for the pages, because the number is the first thing in the line.
Ask for another number: how many tables a paper has. The comment says it after the pages and the figures, and only some comments say it at all.
The first line below takes the third piece of a comment cut at its commas, and the first word of that piece; the second line cuts another comment in the same way:

print(comments[2].split(', ')[2].split(' ')[0])
print(comments[5].split(', ')[2])
3
Hong Kong

The first line gives 3, the number of tables of that paper. The second line runs without an error and answers Hong Kong:
that comment does not mention tables, and the third piece of it is a place.
A cut by place does not know what it cut, and it does not stop when a line is written in another way.
A pattern can ask for a number followed by the word tables wherever it stands in the line, and this is what the lesson teaches.

re.search: the first piece that fits

The module re comes with Python, and import re makes it available.
A pattern is a string that describes the text we look for. It is written as a raw string:
a string with the letter r before the opening quote, such as r'pages'.
In a raw string Python leaves every backslash as it is, and the patterns below use many backslashes, so every pattern in this lesson is a raw string.

The function re.search(pattern, text) looks for the first place in the text where the pattern fits.
It returns a match object that describes the place, or None when the pattern fits nowhere.
The method group() of a match object returns the piece of text that fit.

import re

text = comments[1]
match = re.search(r'pages', text)
print(match)
print(match.group())
print(re.search(r'tables', text))
<re.Match object; span=(2, 7), match='pages'>
pages
None

The match object says that the piece starts at position 2 and ends before position 7.
As with find, a result that can be None is tested with is None before group() is called on it.

Characters and classes

A pattern is read from left to right, and each piece of it fits one character of the text.
A letter fits itself. A character class is a piece that fits any one character of a kind:

PieceFits one character that isExample in a comment
\da digit, 0 to 97
[0-9]a digit: any character in the range in the brackets7
[pf]one of the characters in the bracketsthe p of pages or the f of figures
\wa letter, a digit or an underscorep, 5
\swhite space: a space, a tab or a line breakthe space after a comma
.any character except a line breakany character

Some characters have a meaning of their own in a pattern, such as ., [ and (. To fit the character itself, write a backslash before it: \. fits a dot and \[ fits a square bracket.

print(re.search(r'\d pages', comments[1]))
print(re.search(r'[0-9] pages', comments[1]))
print(re.search(r'figures.\s\w', comments[1]))
<re.Match object; span=(0, 7), match='7 pages'>
<re.Match object; span=(0, 7), match='7 pages'>
<re.Match object; span=(11, 21), match='figures. A'>

Your turn. The comment of another paper begins with 15 pages. What does the pattern \d pages fit in it?
Predict the piece, then run the box.

print(re.search(r'\d pages', comments[9]).group())
5 pages
Show a solution

The pattern fits 5 pages, not 15 pages. The piece \d fits one digit, and the search takes the first place where the whole pattern fits:
the digit 1 is followed by 5, not by a space, so the match starts at the 5.
A number of any length needs a piece that repeats.

Quantifiers: how many times

A quantifier written after a piece says how many times the piece repeats.
It belongs to the piece just before it.

QuantifierMeansExample
+one or more times\d+ fits 7 and 15
*zero or more times\d* fits 15, and also fits nothing
?zero or one time: the piece is optionalpages? fits page and pages
{n}exactly n times\d{4} fits 2026

The function re.findall(pattern, text) returns a list of all the pieces of the text that fit, from left to right.
Each piece starts after the end of the previous one, so two pieces never share a character; for example \d\d on 2610 finds 26 and 10, and not 61 as well.
A piece that appears twice in the text appears twice in the list, like 3 in the second line of the box below.
Each item is a string. In the second line of the box below the pattern finds every run of digits in a comment, and in the third line it finds the identifier of each paper in the list:
four digits, a dot and five digits. The variable soup.text is all the text of the page, without its tags.

print(re.search(r'\d+ pages', comments[9]).group())
print(re.findall(r'\d+', comments[2]))
ids = re.findall(r'\d{4}\.\d{5}', soup.text)
print(len(ids), ids[:3])
15 pages
['4', '3', '3', '2026']
25 ['2610.00106', '2610.00207', '2610.00311']

Groups: taking a part of the match

The pattern \d+ pages fits the text 15 pages, but we want only the number, and group() returns the whole piece.
Round brackets mark the part to take out: (\d+) pages fits the same text, because the brackets do not change what fits, and the piece inside them is also saved.
This is a capturing group. The method group(1) returns the piece of the first pair of brackets, group(2) the piece of the second, counted by the opening bracket from left to right; group() still returns the whole match.
A group returns text, so int converts it to a number.

match = re.search(r'(\d+) pages, (\d+) figures', comments[1])
print(match.group())
print(match.group(1), match.group(2))
print(int(match.group(1)) + 1)
7 pages, 5 figures
7 5
8

When the pattern has groups, re.findall returns the pieces of the groups instead of the whole piece:
a list of strings for one group, and a list of tuples for several groups.

print(re.findall(r'(\d+) pages', comments[2]))
print(re.findall(r'(\d+) pages, (\d+) figures', comments[2]))
['4']
[('4', '3')]

Practice

Your turn. The list comments holds the comment of every paper that has one.
Print the list of the numbers of pages, as whole numbers, of the papers whose comment says how many pages, in the order of comments.

# your code here
Show a hint

Go over the comments in a loop. For each one, re.search with a group around the digits returns a match object or None; test it before you call group(1), and convert the piece with int.

Show a solution
pages = []
for text in comments:
    match = re.search(r'(\d+) pages', text)
    if match is not None:
        pages.append(int(match.group(1)))
print(pages)
[7, 4, 4, 8, 10, 15]
Show a common mistake and why it happens
pages = []
for text in comments:
    match = re.search(r'(\d) pages', text)
    if match is not None:
        pages.append(int(match.group(1)))
print(pages)

The piece \d fits one digit, so the pages of 10 pages and 15 pages become 0 and 5.
The result, [7, 4, 4, 8, 0, 5], has the right length and the wrong numbers.

The size and the date of a submission

The page of a paper has a section called the submission history.
Its text holds, in one line, the date and the size of the first version, [v1], of the paper:
[v1] Wed, 9 Sep 2026 02:40:29 UTC (3,330 KB). A number inside text can be cut with split, replace and strip, as in From One Element to All Entries: find_all, Numbers and Missing Values; a pattern describes the number and its unit directly.

The function history_of requests the saved page of a paper by its identifier and returns the text of its submission history.
Saved pages exist for the first eight papers of the list.

def history_of(paper_id):
    address = base_url + 'arxiv-abs-' + paper_id + '.htm'
    page = BeautifulSoup(requests.get(address).text, 'html.parser')
    return page.find('div', class_='submission-history').text

history = history_of(ids[0])
line = re.search(r'\[v1\]\s+(.*)', history).group(1)
print(line)
Wed, 9 Sep 2026 02:40:29 UTC (3,330 KB)

The pattern \[v1\]\s+(.*) fits the square bracket, v1 and a bracket, then \s+, the line break and the spaces that follow it in the page, and the group (.*):
any number of characters up to the end of the line, because the dot does not fit a line break.

Why Beautiful Soup and a pattern, and not one of them alone?

A pattern alone has to run on the raw HTML, where [v1] is followed by a closing tag:
<strong>[v1]</strong>. The pattern \[v1\]\s+(.*) finds nothing there, and a pattern that includes the tags, \[v1\]</strong>\s+(.*?)<br, works only while the page writes its tags in this way:
with <b> in place of <strong>, or <br> in place of <br/>, it finds nothing and reports no error.

Beautiful Soup alone finds the element and gives its text, but the line still has to be cut out of that text by its place, with split, and the size with replace.
This works while the page keeps the order of its parts and breaks when the order changes; the pattern ([0-9,]+) KB fits the size wherever it stands.

Each tool does what it knows: Beautiful Soup knows the structure of the page, so it finds the element and gives its text without tags; the pattern knows the shape of a text, so it takes the size and the date wherever they stand in the line.
On these eight saved pages one tool would also give the right answer; the two together keep the code from depending on the tags and on the places.

In the line, the size is digits and commas followed by KB, and the date is a day, a month and a year.
The character class [0-9,] fits a digit or a comma, a comma has no special meaning inside the brackets, so [0-9,]+ fits 3,330.
The piece \d\d? is a digit and an optional second digit: a day of the month has one or two digits.
The text 3,330 is still text, and replace removes the comma before int converts it.

size = re.search(r'([0-9,]+) KB', line).group(1)
print(size)
print(int(size.replace(',', '')))
print(re.findall(r'(\d\d?) (\w+) (\d{4})', line))
3,330
3330
[('9', 'Sep', '2026')]

The dot and the shortest match

The subjects of a paper are written in a line such as Hardware Architecture (cs.AR); Artificial Intelligence (cs.AI).
The code of each subject is inside round brackets. In the pattern, \( and \) fit the round brackets themselves, and the pair of brackets without a backslash is the group that saves what is between them.

The box below defines the function subjects_of, which returns the subjects line of one entry, and builds the list subjects for the 25 papers.
It only prepares the data with Beautiful Soup, as in the earlier lessons; the work with patterns starts in the box after it.
The second paper has three subjects.

def subjects_of(entry):
    box = entry.find('div', class_='list-subjects')
    return box.text.replace('Subjects:', '').strip()

subjects = [subjects_of(e) for e in soup.find_all('dd')]
print(subjects[1])
Hardware Architecture (cs.AR); Artificial Intelligence (cs.AI); Image and Video Processing (eess.IV)

The piece .* fits any number of characters, and it takes as many as it can while the whole pattern still fits:
it is greedy. In \((.*)\) the group starts after the first opening bracket and runs to the last closing bracket of the line.
A ? after a quantifier makes it take as few characters as it can, the shortest match:
.*? stops at the first closing bracket that lets the pattern fit.

print(re.findall(r'\((.*)\)', subjects[1]))
print(re.findall(r'\((.*?)\)', subjects[1]))
['cs.AR); Artificial Intelligence (cs.AI); Image and Video Processing (eess.IV']
['cs.AR', 'cs.AI', 'eess.IV']

The same character, ?, means two things: after a piece it makes the piece optional, and after a quantifier it makes the quantifier take as little as possible.

Practice

Your turn. The list subjects holds the subjects line of each of the 25 papers.
The code of a subject is inside round brackets. Print the number of papers that have more than one subject.

# your code here
Show a hint

re.findall with a group around the code returns the codes of one paper as a list; a paper has more than one subject when the list has more than one item.
Make sure the group stops at the first closing bracket.

Show a solution
many = 0
for text in subjects:
    codes = re.findall(r'\((.*?)\)', text)
    if len(codes) > 1:
        many = many + 1
print(many)
11
Show a common mistake and why it happens
many = 0
for text in subjects:
    codes = re.findall(r'\((.*)\)', text)
    if len(codes) > 1:
        many = many + 1
print(many)

The greedy .* takes everything from the first opening bracket to the last closing bracket, so every paper gives exactly one piece, and the result is 0.

Testing a pattern in a tool

A pattern that looks right can fit something else, so we test it on real text before we run it on a thousand pages.
The Regular Expression Lab of this course is such a tester: the text goes in one box and the pattern in another, every piece that fits is highlighted, and a list explains each part of the pattern in plain words.
In the lab a pattern is written without the quotes and without the letter r.

To try it, open the lab, keep the comments of the papers as the text, and write (\d+) pages, (\d+) figures as the pattern:
the lab marks the whole match and the two groups of the comments that fit.
Then change 7 pages in the text to 1 page and see why the pattern no longer fits that line.

When a regular expression is not the tool

A regular expression reads text and knows nothing of a page.
Beautiful Soup builds the tree of the elements and finds one by its tag, its class or its attribute.
A pattern applied to the raw HTML text of a page depends on how the tags happen to be written, and it fails quietly:
it returns an empty list and no error. The box counts, with the pattern and with Beautiful Soup, the identifiers and the comment elements of the list:

print(len(re.findall(r'\d{4}\.\d{5}', page_text)))
print(len(re.findall(r'\d{4}\.\d{5}', soup.text)))
print(len(re.findall(r'<div class="list-comments">', page_text)))
print(len(soup.find_all('div', class_='list-comments')))
300
25
0
12

The HTML repeats each identifier 12 times, in the addresses and the attributes of its links (25 times 12 is 300), and the text of the page gives 25.
The pattern finds nothing for two reasons: the page writes the attribute with single quotes, class='list-comments mathjax', and the pattern has double quotes; and the class has a second word, mathjax, so <div class="list-comments"> would not fit even with the right quotes.
class_='list-comments' does not depend on either, and finds the 12 elements.

The division of work is therefore this: Beautiful Soup finds the element that holds the text, a pattern takes the number, the date or the code out of the text of that element.
A pattern also describes a shape and not a meaning: in the abstract of the paper EdgeDAE, \d+\.\d+ fits the percentages 52.5 and 38.7, and also 2.10, which is a ratio of throughput.
We look at the pieces that fit, count them, and test the pattern on texts that should not fit.

Keep in mind

  • Beautiful Soup finds an element by the structure of the page; a regular expression finds a pattern inside a piece of text. Take the text of the element, then search it with a pattern.
  • A pattern is a raw string, r'...'. re.search returns a match object, whose group() is the piece that fit, or None; re.findall returns a list of all the pieces that fit, as text.
  • \d, \w, \s, [0-9], [abc] and . fit one character; a backslash before ., [ or ( fits the character itself.
  • +, *, ? and {n} say how many times a piece repeats; round brackets save a part of the match, and with groups re.findall returns the groups.
  • .* takes as much as it can and .*? as little as it can; a group of the form \((.*?)\) stops at the first closing bracket.
  • A piece taken out of text is text: int converts digits, after replace removes a comma. A pattern that fits the examples can still fit other text, so test it and count what it finds.

Self-study, importance 1 This part is for self-study: it is not taught in the lecture, and you read it on your own. Compiling a pattern once and using it many times. It helps with: naming a pattern and reusing it in a function.

re.compile: a pattern with a name

A pattern that a program uses many times can be built once. The function re.compile(pattern) returns a compiled pattern, an object that holds the pattern and has the methods search and findall of its own, so that compiled.search(text) does what re.search(pattern, text) does.
The function pages_of below returns the number of pages of a comment, or None, with a pattern that is built once.

pages_pattern = re.compile(r'(\d+) pages')

def pages_of(text):
    match = pages_pattern.search(text)
    if match is None:
        return None
    return int(match.group(1))

all_pages = [pages_of(text) for text in comments]
print(all_pages)
known = [pages for pages in all_pages if pages is not None]
print(len(known), max(known), sum(known) / len(known))
[None, 7, 4, 4, None, None, 8, None, 10, 15, None, None]
6 15 8.0

The six papers that say how many pages they have are the same six as in the function that cuts the text with split, in From One Element to All Entries: find_all, Numbers and Missing Values; here the pattern finds the number wherever it stands in the comment.

Self-study, importance 2 This part is for self-study: it is not taught in the lecture, and you read it on your own. A practice task that reads several pages and takes a size from each. It helps with: a regular expression applied to many pages.

Practice: several pages

Your turn. The function history_of returns the text of the submission history of a paper by its identifier, and the list ids holds the identifiers of the 25 papers; saved pages exist for the first eight.
Print the largest size, as a whole number of KB, among the first eight papers.

# your code here
Show a hint

Go over ids[:8], and for each identifier take the text of the size with a group around the digits and the comma, remove the comma, and convert it with int.
Compare numbers, not texts.

Show a solution
sizes = []
for paper_id in ids[:8]:
    history = history_of(paper_id)
    size = re.search(r'([0-9,]+) KB', history).group(1)
    sizes.append(int(size.replace(',', '')))
print(max(sizes))
19279
Show a common mistake and why it happens
sizes = []
for paper_id in ids[:8]:
    history = history_of(paper_id)
    size = re.search(r'([0-9,]+) KB', history).group(1)
    sizes.append(size)
print(max(sizes))

The sizes stay as text, and max compares texts character by character:
'866' is larger than '19,279' because '8' comes after '1'. The program prints 866, a size that is not the largest.