{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c001",
   "metadata": {},
   "source": [
    "# Patterns in Text: Regular Expressions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c002",
   "metadata": {},
   "source": [
    "In this lesson we learn what a [regular expression](https://dvirross.com/courses/intro-data-science/glossary#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.\n",
    "\n",
    "## Where is the number of pages?\n",
    "\n",
    "Authors who post a paper on [arXiv](https://arxiv.org) 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](https://dvirross.com/courses/intro-data-science/data-collection-find-all). 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`.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c003",
   "metadata": {},
   "source": [
    "## Setup: the libraries and the check function\n",
    "\n",
    "No account and no key are needed. The next cell imports `requests` and `beautifulsoup4` (Colab has both; the cell installs them if the session does not). The pages that the code reads are saved copies of arXiv pages, kept on the public site of the course, so the numbers are the same for everyone. This notebook sends no request to arXiv itself."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c004",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:57.980236Z",
     "iopub.status.busy": "2026-11-22T03:33:57.980015Z",
     "iopub.status.idle": "2026-11-22T03:33:58.027852Z",
     "shell.execute_reply": "2026-11-22T03:33:58.024985Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "requests 2.34.2 | beautifulsoup4 4.15.0\n"
     ]
    }
   ],
   "source": [
    "try:\n",
    "    import bs4, requests\n",
    "except ImportError:\n",
    "    !pip install -q requests beautifulsoup4\n",
    "    import bs4, requests\n",
    "print('requests', requests.__version__, '| beautifulsoup4', bs4.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c005",
   "metadata": {},
   "source": [
    "The next cell defines the function `check(task_number)`. After you run the cell of a task, run the cell under it: `check` runs your cell again, collects what it prints, and compares it with the expected output. It tells you whether the output is right, and where it differs if not; it never shows the solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "c006",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.029541Z",
     "iopub.status.busy": "2026-11-22T03:33:58.029284Z",
     "iopub.status.idle": "2026-11-22T03:33:58.037982Z",
     "shell.execute_reply": "2026-11-22T03:33:58.037088Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast, contextlib, hashlib, io\n",
    "\n",
    "# The expected output of each task, as hashes of its lines (the solutions are not stored here).\n",
    "EXPECTED = {int(k): v for k, v in {\n",
    "    '1': [\n",
    "        '79eb0b37c90d'\n",
    "    ],\n",
    "    '2': [\n",
    "        '4fc82b26aecb'\n",
    "    ],\n",
    "    '3': [\n",
    "        '9b7d87bc5316'\n",
    "    ]\n",
    "}.items()}\n",
    "\n",
    "\n",
    "def check(task):\n",
    "    \"\"\"Run the last cell that ran (not a check) again and compare what it prints with the expected output of the task.\"\"\"\n",
    "    if task not in EXPECTED:\n",
    "        print('There is no such task: ', task)\n",
    "        return\n",
    "    cells = [s for s in In[:-1] if s.strip() and not s.lstrip().startswith('check(')]   # In: the cells that ran, kept by IPython\n",
    "    tree = ast.parse(cells[-1] if cells else '')\n",
    "    last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None   # a bare last expression counts as printed\n",
    "    out = io.StringIO()\n",
    "    try:\n",
    "        with contextlib.redirect_stdout(out):\n",
    "            exec(compile(tree, '<task>', 'exec'), globals())\n",
    "            if last is not None:\n",
    "                value = eval(compile(ast.Expression(last.value), '<task>', 'eval'), globals())\n",
    "                if value is not None:\n",
    "                    print(repr(value))\n",
    "    except Exception as error:\n",
    "        print('The cell raised an error:', type(error).__name__ + ':', error)\n",
    "        return\n",
    "    got = [hashlib.sha256(line.rstrip().encode()).hexdigest()[:12] for line in out.getvalue().rstrip().splitlines()]\n",
    "    want = EXPECTED[task]\n",
    "    if not got:\n",
    "        print('Nothing was printed. Print the answer in the task cell, run it, and run `check` straight after it.')\n",
    "    elif len(got) != len(want):\n",
    "        print('The cell printed {got} line(s) and the task expects {want}. Re-read the task and the hint.'.format(got=len(got), want=len(want)))\n",
    "    elif got != want:\n",
    "        print('Line {k} is different from the expected output. Re-read the task and the hint.'.format(k=next(i for i in range(len(want)) if got[i] != want[i]) + 1))\n",
    "    else:\n",
    "        print('OK: the output is as expected.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c007",
   "metadata": {},
   "source": [
    "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](https://dvirross.com/courses/intro-data-science/data-collection-beautifulsoup), 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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c008",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.039969Z",
     "iopub.status.busy": "2026-11-22T03:33:58.039809Z",
     "iopub.status.idle": "2026-11-22T03:33:58.079174Z",
     "shell.execute_reply": "2026-11-22T03:33:58.076446Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "12\n",
      "7 pages, 5 figures. Accepted to ASP-DAC 2027\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "\n",
    "base_url = (\n",
    "    'https://dvirross.com/materials/courses/'\n",
    "    'intro-data-science/'\n",
    ")\n",
    "list_url = base_url + 'arxiv-cs-ar-2026-10.htm'\n",
    "page_text = requests.get(list_url).text\n",
    "soup = BeautifulSoup(page_text, 'html.parser')\n",
    "\n",
    "boxes = soup.find_all('div', class_='list-comments')\n",
    "comments = [\n",
    "    box.text.replace('Comments:', '').strip()\n",
    "    for box in boxes\n",
    "]\n",
    "print(len(comments))\n",
    "print(comments[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c009",
   "metadata": {},
   "source": [
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "c010",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.080910Z",
     "iopub.status.busy": "2026-11-22T03:33:58.080747Z",
     "iopub.status.idle": "2026-11-22T03:33:58.085117Z",
     "shell.execute_reply": "2026-11-22T03:33:58.084154Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "Hong Kong\n"
     ]
    }
   ],
   "source": [
    "print(comments[2].split(', ')[2].split(' ')[0])\n",
    "print(comments[5].split(', ')[2])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c011",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## `re.search`: the first piece that fits\n",
    "\n",
    "The module `re` comes with Python, and `import re` makes it available. A **[pattern](https://dvirross.com/courses/intro-data-science/glossary#pattern)** is a string that describes the text we look for. It is written as a **[raw string](https://dvirross.com/courses/intro-data-science/glossary#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.\n",
    "\n",
    "The function `re.search(pattern, text)` looks for the first place in the text where the pattern fits. It returns a **[match object](https://dvirross.com/courses/intro-data-science/glossary#match)** 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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c012",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.086549Z",
     "iopub.status.busy": "2026-11-22T03:33:58.086399Z",
     "iopub.status.idle": "2026-11-22T03:33:58.090229Z",
     "shell.execute_reply": "2026-11-22T03:33:58.089118Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<re.Match object; span=(2, 7), match='pages'>\n",
      "pages\n",
      "None\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "text = comments[1]\n",
    "match = re.search(r'pages', text)\n",
    "print(match)\n",
    "print(match.group())\n",
    "print(re.search(r'tables', text))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c013",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "## Characters and classes\n",
    "\n",
    "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:\n",
    "\n",
    "| Piece | Fits one character that is | Example in a comment |\n",
    "|---|---|---|\n",
    "| `\\d` | a digit, 0 to 9 | `7` |\n",
    "| `[0-9]` | a digit: any character in the range in the brackets | `7` |\n",
    "| `[pf]` | one of the characters in the brackets | the `p` of `pages` or the `f` of `figures` |\n",
    "| `\\w` | a letter, a digit or an underscore | `p`, `5` |\n",
    "| `\\s` | white space: a space, a tab or a line break | the space after a comma |\n",
    "| `.` | any character except a line break | any character |\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "c014",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.091698Z",
     "iopub.status.busy": "2026-11-22T03:33:58.091538Z",
     "iopub.status.idle": "2026-11-22T03:33:58.095900Z",
     "shell.execute_reply": "2026-11-22T03:33:58.094970Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<re.Match object; span=(0, 7), match='7 pages'>\n",
      "<re.Match object; span=(0, 7), match='7 pages'>\n",
      "<re.Match object; span=(11, 21), match='figures. A'>\n"
     ]
    }
   ],
   "source": [
    "print(re.search(r'\\d pages', comments[1]))\n",
    "print(re.search(r'[0-9] pages', comments[1]))\n",
    "print(re.search(r'figures.\\s\\w', comments[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c015",
   "metadata": {},
   "source": [
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c016",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.097524Z",
     "iopub.status.busy": "2026-11-22T03:33:58.097310Z",
     "iopub.status.idle": "2026-11-22T03:33:58.100274Z",
     "shell.execute_reply": "2026-11-22T03:33:58.099355Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5 pages\n"
     ]
    }
   ],
   "source": [
    "print(re.search(r'\\d pages', comments[9]).group())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c017",
   "metadata": {},
   "source": [
    "## Quantifiers: how many times\n",
    "\n",
    "A **quantifier** written after a piece says how many times the piece repeats. It belongs to the piece just before it.\n",
    "\n",
    "| Quantifier | Means | Example |\n",
    "|---|---|---|\n",
    "| `+` | one or more times | `\\d+` fits `7` and `15` |\n",
    "| `*` | zero or more times | `\\d*` fits `15`, and also fits nothing |\n",
    "| `?` | zero or one time: the piece is optional | `pages?` fits `page` and `pages` |\n",
    "| `{n}` | exactly n times | `\\d{4}` fits `2026` |\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "c018",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.101462Z",
     "iopub.status.busy": "2026-11-22T03:33:58.101298Z",
     "iopub.status.idle": "2026-11-22T03:33:58.105231Z",
     "shell.execute_reply": "2026-11-22T03:33:58.104253Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15 pages\n",
      "['4', '3', '3', '2026']\n",
      "25 ['2610.00106', '2610.00207', '2610.00311']\n"
     ]
    }
   ],
   "source": [
    "print(re.search(r'\\d+ pages', comments[9]).group())\n",
    "print(re.findall(r'\\d+', comments[2]))\n",
    "ids = re.findall(r'\\d{4}\\.\\d{5}', soup.text)\n",
    "print(len(ids), ids[:3])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c019",
   "metadata": {},
   "source": [
    "## Groups: taking a part of the match\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/glossary#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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c020",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.106626Z",
     "iopub.status.busy": "2026-11-22T03:33:58.106489Z",
     "iopub.status.idle": "2026-11-22T03:33:58.109963Z",
     "shell.execute_reply": "2026-11-22T03:33:58.108838Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7 pages, 5 figures\n",
      "7 5\n",
      "8\n"
     ]
    }
   ],
   "source": [
    "match = re.search(r'(\\d+) pages, (\\d+) figures', comments[1])\n",
    "print(match.group())\n",
    "print(match.group(1), match.group(2))\n",
    "print(int(match.group(1)) + 1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c021",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c022",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.111189Z",
     "iopub.status.busy": "2026-11-22T03:33:58.111052Z",
     "iopub.status.idle": "2026-11-22T03:33:58.114416Z",
     "shell.execute_reply": "2026-11-22T03:33:58.113473Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['4']\n",
      "[('4', '3')]\n"
     ]
    }
   ],
   "source": [
    "print(re.findall(r'(\\d+) pages', comments[2]))\n",
    "print(re.findall(r'(\\d+) pages, (\\d+) figures', comments[2]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c023",
   "metadata": {},
   "source": [
    "### Practice\n",
    "\n",
    "**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`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c024",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.116199Z",
     "iopub.status.busy": "2026-11-22T03:33:58.116058Z",
     "iopub.status.idle": "2026-11-22T03:33:58.118645Z",
     "shell.execute_reply": "2026-11-22T03:33:58.117740Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c025",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "[<number>, <number>, <number>, <number>, <number>, <number>]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "c026",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.119847Z",
     "iopub.status.busy": "2026-11-22T03:33:58.119719Z",
     "iopub.status.idle": "2026-11-22T03:33:58.122622Z",
     "shell.execute_reply": "2026-11-22T03:33:58.121668Z"
    }
   },
   "outputs": [],
   "source": [
    "check(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c027",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c028",
   "metadata": {},
   "source": [
    "## The size and the date of a submission\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/data-collection-find-all); a pattern describes the number and its unit directly.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "c029",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.123816Z",
     "iopub.status.busy": "2026-11-22T03:33:58.123685Z",
     "iopub.status.idle": "2026-11-22T03:33:58.139240Z",
     "shell.execute_reply": "2026-11-22T03:33:58.138240Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wed, 9 Sep 2026 02:40:29 UTC (3,330 KB)\n"
     ]
    }
   ],
   "source": [
    "def history_of(paper_id):\n",
    "    address = base_url + 'arxiv-abs-' + paper_id + '.htm'\n",
    "    page = BeautifulSoup(requests.get(address).text, 'html.parser')\n",
    "    return page.find('div', class_='submission-history').text\n",
    "\n",
    "history = history_of(ids[0])\n",
    "line = re.search(r'\\[v1\\]\\s+(.*)', history).group(1)\n",
    "print(line)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c030",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c031",
   "metadata": {},
   "source": [
    "**Why Beautiful Soup and a pattern, and not one of them alone?**"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c032",
   "metadata": {},
   "source": [
    "**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.\n",
    "\n",
    "**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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c033",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "c034",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.140687Z",
     "iopub.status.busy": "2026-11-22T03:33:58.140536Z",
     "iopub.status.idle": "2026-11-22T03:33:58.144080Z",
     "shell.execute_reply": "2026-11-22T03:33:58.143085Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3,330\n",
      "3330\n",
      "[('9', 'Sep', '2026')]\n"
     ]
    }
   ],
   "source": [
    "size = re.search(r'([0-9,]+) KB', line).group(1)\n",
    "print(size)\n",
    "print(int(size.replace(',', '')))\n",
    "print(re.findall(r'(\\d\\d?) (\\w+) (\\d{4})', line))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c035",
   "metadata": {},
   "source": [
    "## The dot and the shortest match\n",
    "\n",
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "c036",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.145278Z",
     "iopub.status.busy": "2026-11-22T03:33:58.145147Z",
     "iopub.status.idle": "2026-11-22T03:33:58.150018Z",
     "shell.execute_reply": "2026-11-22T03:33:58.149009Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hardware Architecture (cs.AR); Artificial Intelligence (cs.AI); Image and Video Processing (eess.IV)\n"
     ]
    }
   ],
   "source": [
    "def subjects_of(entry):\n",
    "    box = entry.find('div', class_='list-subjects')\n",
    "    return box.text.replace('Subjects:', '').strip()\n",
    "\n",
    "subjects = [subjects_of(e) for e in soup.find_all('dd')]\n",
    "print(subjects[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c037",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c038",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.151297Z",
     "iopub.status.busy": "2026-11-22T03:33:58.151115Z",
     "iopub.status.idle": "2026-11-22T03:33:58.155492Z",
     "shell.execute_reply": "2026-11-22T03:33:58.153514Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['cs.AR); Artificial Intelligence (cs.AI); Image and Video Processing (eess.IV']\n",
      "['cs.AR', 'cs.AI', 'eess.IV']\n"
     ]
    }
   ],
   "source": [
    "print(re.findall(r'\\((.*)\\)', subjects[1]))\n",
    "print(re.findall(r'\\((.*?)\\)', subjects[1]))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c039",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "### Practice\n",
    "\n",
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "c040",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.156860Z",
     "iopub.status.busy": "2026-11-22T03:33:58.156719Z",
     "iopub.status.idle": "2026-11-22T03:33:58.161490Z",
     "shell.execute_reply": "2026-11-22T03:33:58.158452Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c041",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "c042",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.162830Z",
     "iopub.status.busy": "2026-11-22T03:33:58.162681Z",
     "iopub.status.idle": "2026-11-22T03:33:58.168237Z",
     "shell.execute_reply": "2026-11-22T03:33:58.164833Z"
    }
   },
   "outputs": [],
   "source": [
    "check(2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c043",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> `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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c044",
   "metadata": {},
   "source": [
    "## Testing a pattern in a tool\n",
    "\n",
    "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](https://dvirross.com/courses/intro-data-science/data-collection-regex-practice) 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`.\n",
    "\n",
    "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.\n",
    "\n",
    "## When a regular expression is not the tool\n",
    "\n",
    "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:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "c045",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.169794Z",
     "iopub.status.busy": "2026-11-22T03:33:58.169652Z",
     "iopub.status.idle": "2026-11-22T03:33:58.177221Z",
     "shell.execute_reply": "2026-11-22T03:33:58.174047Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "300\n",
      "25\n",
      "0\n",
      "12\n"
     ]
    }
   ],
   "source": [
    "print(len(re.findall(r'\\d{4}\\.\\d{5}', page_text)))\n",
    "print(len(re.findall(r'\\d{4}\\.\\d{5}', soup.text)))\n",
    "print(len(re.findall(r'<div class=\"list-comments\">', page_text)))\n",
    "print(len(soup.find_all('div', class_='list-comments')))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c046",
   "metadata": {},
   "source": [
    "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.\n",
    "\n",
    "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.\n",
    "\n",
    "## Keep in mind\n",
    "\n",
    "- 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.\n",
    "- 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.\n",
    "- `\\d`, `\\w`, `\\s`, `[0-9]`, `[abc]` and `.` fit one character; a backslash before `.`, `[` or `(` fits the character itself.\n",
    "- `+`, `*`, `?` 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.\n",
    "- `.*` takes as much as it can and `.*?` as little as it can; a group of the form `\\((.*?)\\)` stops at the first closing bracket.\n",
    "- 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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c047",
   "metadata": {},
   "source": [
    "> **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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c048",
   "metadata": {},
   "source": [
    "## `re.compile`: a pattern with a name\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "c049",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.178842Z",
     "iopub.status.busy": "2026-11-22T03:33:58.178663Z",
     "iopub.status.idle": "2026-11-22T03:33:58.184958Z",
     "shell.execute_reply": "2026-11-22T03:33:58.181587Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[None, 7, 4, 4, None, None, 8, None, 10, 15, None, None]\n",
      "6 15 8.0\n"
     ]
    }
   ],
   "source": [
    "pages_pattern = re.compile(r'(\\d+) pages')\n",
    "\n",
    "def pages_of(text):\n",
    "    match = pages_pattern.search(text)\n",
    "    if match is None:\n",
    "        return None\n",
    "    return int(match.group(1))\n",
    "\n",
    "all_pages = [pages_of(text) for text in comments]\n",
    "print(all_pages)\n",
    "known = [pages for pages in all_pages if pages is not None]\n",
    "print(len(known), max(known), sum(known) / len(known))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c050",
   "metadata": {},
   "source": [
    "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](https://dvirross.com/courses/intro-data-science/data-collection-find-all); here the pattern finds the number wherever it stands in the comment."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c051",
   "metadata": {},
   "source": [
    "> **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."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c052",
   "metadata": {},
   "source": [
    "### Practice: several pages\n",
    "\n",
    "**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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c053",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.186621Z",
     "iopub.status.busy": "2026-11-22T03:33:58.186465Z",
     "iopub.status.idle": "2026-11-22T03:33:58.188934Z",
     "shell.execute_reply": "2026-11-22T03:33:58.188083Z"
    }
   },
   "outputs": [],
   "source": [
    "# Your turn"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c054",
   "metadata": {},
   "source": [
    "**Expected output (the numbers are hidden)**\n",
    "\n",
    "```text\n",
    "<number>\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "c055",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2026-11-22T03:33:58.192006Z",
     "iopub.status.busy": "2026-11-22T03:33:58.191858Z",
     "iopub.status.idle": "2026-11-22T03:33:58.195495Z",
     "shell.execute_reply": "2026-11-22T03:33:58.193920Z"
    }
   },
   "outputs": [],
   "source": [
    "check(3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c056",
   "metadata": {},
   "source": [
    "> **Hint**\n",
    ">\n",
    "> 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."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
