{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "3a7d8b47",
   "metadata": {},
   "source": [
    "# Regex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "38f16749",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent  # ← Add project root, not chapters\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle, structshape\n",
    "from shared.download import download\n",
    "\n",
    "# Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a8f141fd",
   "metadata": {},
   "source": [
    "String methods allow you to search and manipulate text to a certain extent. A **regular expression** (regex) is a sequence of characters that defines a **search pattern** to search, match, and manipulate text in more powerful ways that go beyond simple string methods. For example:\n",
    "\n",
    "| Task | Use |\n",
    "|---|---|\n",
    "| Check if string starts with 'http' | `str.startswith()` |\n",
    "| Replace all spaces with underscores | `str.replace()` |\n",
    "| Extract all email addresses from text | regex |\n",
    "| Validate a phone number format | regex |\n",
    "| Find words matching a complex pattern | regex |\n",
    "\n",
    "The rule of thumb: if the pattern is **fixed and simple**, use string methods. If the pattern is **variable or complex**, use regex."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-5b992f30",
   "metadata": {},
   "source": [
    "```{index} regular expression\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7ecec41c",
   "metadata": {},
   "source": [
    "For example, to search a pattern in a text, you can use the `find()` string method, which returns an index if it finds the pattern."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b979b61",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "0aa5f24b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = \"I am Dracula; and I bid you welcome, Mr. Harker, to my house.\"\n",
    "pattern = 'Dracula'\n",
    "text.find(pattern)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5b992f30",
   "metadata": {},
   "source": [
    "## Backslashes in Regex Patterns\n",
    "\n",
    "In {ref}`Escape Sequences and Raw Strings <ch08-escape-sequences>` you saw that Python treats a backslash in a string literal as the start of an escape sequence, so `\"\\n\"` is a single newline character. Regex patterns also use backslashes, but for their own purposes: `\\d` means \"any digit,\" and `\\.` means \"a literal dot.\" The Metacharacters section below covers these sequences.\n",
    "\n",
    "So a regex pattern passes through two layers of backslash processing:\n",
    "\n",
    "1. **Python** reads the string literal and turns escape sequences such as `\\n`, `\\t`, and `\\b` into single characters.\n",
    "2. The **regex engine** then reads the resulting string and gives its own meaning to sequences such as `\\d`, `\\w`, and `\\b`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6500b3b8",
   "metadata": {},
   "source": [
    "### Raw Strings"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-6500b3b8",
   "metadata": {},
   "source": [
    "```{index} raw string\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6826c201",
   "metadata": {},
   "source": [
    "A raw string, prefixed with **`r`**, turns off the first layer: Python keeps every backslash as an ordinary character, so the regex engine receives exactly the pattern you typed. That is why regex patterns are almost always written as raw strings.\n",
    "\n",
    "The two layers disagree about `\\b`. To Python, `\"\\b\"` is a backspace character; to the regex engine, `\\b` is a word boundary. `repr()` shows what each string actually contains:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c37dbeaf",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'\\x08cat\\x08'\n",
      "'\\\\bcat\\\\b'\n"
     ]
    }
   ],
   "source": [
    "print(repr(\"\\bcat\\b\"))    # '\\x08cat\\x08': Python turned each \\b into a backspace character\n",
    "print(repr(r\"\\bcat\\b\"))   # '\\\\bcat\\\\b': the backslashes survive for the regex engine"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "018d11be",
   "metadata": {},
   "source": [
    "Without a raw string, you have to double every backslash so that one survives the first layer. In the cell below, compare how many backslashes each version needs to produce the same characters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "1e887253",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\\\\\n",
      "\\\\\n",
      "\\\\\\n\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "print('\\\\\\\\')                  # normal string: each \\\\ becomes one backslash, so this prints \\\\\n",
    "print(r'\\\\')                   # raw string: both backslashes are kept, so this also prints \\\\\n",
    "print(r'\\\\\\n')                 # raw string: three backslashes and an n, printed as \\\\\\n\n",
    "print(r'\\\\\\n' == '\\\\\\\\\\\\n')    # True: the normal string needs six backslashes for the same four characters"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90a7cb99",
   "metadata": {},
   "source": [
    "In short, a raw string tells Python to treat each backslash as an ordinary character, so you can write a regex pattern once, exactly as the regex engine should see it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dab4e57",
   "metadata": {},
   "source": [
    "## The `re` Module\n",
    "\n",
    "Python's built-in `re` module provides regex support. The 7 most commonly used regex functions are:\n",
    "\n",
    "| Function | Description | Sample Syntax | Return |\n",
    "|---|---|---|---|\n",
    "| `re.search()` | Find **first** match anywhere in the string | `re.search(pattern, text)` | **`Match` object** or `None` |\n",
    "| `re.match()` | Match only at the **start** of the string | `re.match(pattern, text)` | **`Match` object** or `None` |\n",
    "| `re.fullmatch()` | Match the entire string against the pattern | `re.fullmatch(pattern, text)` | **`Match` object** or `None` |\n",
    "| `re.findall()` | Find **all** matches; return as a **list** | `re.findall(pattern, text)` | `list` of strings or tuples, depending on capture groups |\n",
    "| `re.finditer()` | Find **all** matches, one `Match` object at a time | `re.finditer(pattern, text)` | iterator of **`Match` objects** |\n",
    "| `re.sub()` | Find and replace matches | `re.sub(pattern, repl, text)` | `str` |\n",
    "| `re.split()` | Split string on a pattern | `re.split(pattern, text)` | `list` of strings; captured separators are included when the pattern has groups |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-3dab4e57",
   "metadata": {},
   "source": [
    "```{index} re module, re.search(), re.findall(), re.finditer()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1950d45",
   "metadata": {},
   "source": [
    "### The `Match` Object\n",
    "\n",
    "`re.search()`, `re.match()`, and `re.fullmatch()` return a `Match` object when the pattern matches and `None` when it does not. For example, `re.search(pattern, text)` scans `text` and returns a `Match` object for the **first** location where `pattern` is found.\n",
    "\n",
    "A `Match` object has the following commonly used attributes and methods:\n",
    "\n",
    "| Attribute / Method | Description | Example |\n",
    "|---|---|---|\n",
    "| `.group()` | Returns the matched substring | `m.group()` → `'Dracula'` |\n",
    "| `.start()` | Index where the match begins | `m.start()` → `5` |\n",
    "| `.end()` | Index where the match ends | `m.end()` → `12` |\n",
    "| `.span()` | Tuple of `(start, end)` | `m.span()` → `(5, 12)` |\n",
    "| `.string` | The original string that was searched | `m.string` → `'I am Dracula...'` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-d1950d45",
   "metadata": {},
   "source": [
    "```{index} Match object, group()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "62713517",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<re.Match object; span=(5, 12), match='Dracula'>"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "text = \"I am Dracula; and I bid you welcome, Mr. Harker, to my house.\"\n",
    "pattern = 'Dracula'\n",
    "\n",
    "result = re.search(pattern, text)     ### pattern: Dracula; text: the line\n",
    "result                              ### the Match object"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ecf6690b",
   "metadata": {},
   "source": [
    "The `Match` object records both the text that was searched (the `.string` attribute) and where the match sits inside it. `.end()` is one past the last matched character, so `text[m.start():m.end()]` gives the same string as `m.group()`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6fdd12a9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I am Dracula; and I bid you welcome, Mr. Harker, to my house.\n",
      "Dracula\n",
      "5\n",
      "12\n",
      "(5, 12)\n"
     ]
    }
   ],
   "source": [
    "print(result.string)\n",
    "print(result.group())\n",
    "print(result.start())\n",
    "print(result.end())\n",
    "print(result.span())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d38ad650",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "`.group()` returns the **matched substring from the text**: the portion of the text that the pattern matched against. In simple cases like `re.search('Dracula', text)`, the match equals the pattern string. But with a pattern that uses metacharacters (covered in the Metacharacters section below), such as a pattern for any dollar amount, `.group()` returns the actual text that matched, like `'$42.99'`, not the pattern expression itself.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2fb89ac5",
   "metadata": {},
   "source": [
    "If the pattern doesn't appear in the text, the return value from `search` is `None`. So you can check whether the search was successful by checking whether the result is `None`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "613a304d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = re.search('Count', text)\n",
    "print(result)\n",
    "\n",
    "result is None"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-guard-match",
   "metadata": {},
   "source": [
    "Before accessing a match's methods or attributes, check that a match exists. Calling `.group()` on `None` raises `AttributeError`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "ch08-guard-match-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dracula (5, 12)\n",
      "Count not found\n"
     ]
    }
   ],
   "source": [
    "for name in ['Dracula', 'Count']:\n",
    "    match = re.search(name, text)\n",
    "    if match is None:\n",
    "        print(name, 'not found')\n",
    "    else:\n",
    "        print(match.group(), match.span())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffef1c34",
   "metadata": {},
   "source": [
    "The other functions in the table take a pattern the same way. The cell below runs `findall()`, `finditer()`, `search()`, `sub()`, and `split()` with literal patterns, which match only the exact characters you type. Use `finditer()` instead of `findall()` when you need the position of every match, not just its text. The Metacharacters section shows how to write patterns that match variable text, such as any price or any run of spaces."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "daa3fba6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['cat', 'cat']\n",
      "cat (4, 7)\n",
      "cat (36, 39)\n",
      "cat\n",
      "4 7\n",
      "The dog sat on the mat with another dog.\n",
      "['one', 'two', 'three']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "text = \"The cat sat on the mat with another cat.\"\n",
    "\n",
    "# findall: get all matches\n",
    "print(re.findall(\"cat\", text))              # ['cat', 'cat']\n",
    "\n",
    "# finditer: one Match object per match\n",
    "for m in re.finditer(\"cat\", text):\n",
    "    print(m.group(), m.span())              # cat (4, 7), then cat (36, 39)\n",
    "\n",
    "# search: first match object\n",
    "m = re.search(\"cat\", text)\n",
    "print(m.group())                            # 'cat'\n",
    "print(m.start(), m.end())                   # position in string\n",
    "\n",
    "# sub: replace\n",
    "print(re.sub(\"cat\", \"dog\", text))           # every 'cat' becomes 'dog'\n",
    "\n",
    "# split\n",
    "print(re.split(\", \", \"one, two, three\"))    # ['one', 'two', 'three']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8c5d4f62",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: The Match Object\n",
    "# Difficulty: Basic\n",
    "# 1. Use re.search() to find the word 'Order' in text\n",
    "# 2. Print the matched string, start index, end index, and span\n",
    "# 3. Search text for 'Invoice' and print whether the result is None\n",
    "import re\n",
    "text = \"Customer ID: 4892, Order date: 2024-03-15\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "6408257c",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Order\n",
      "19\n",
      "24\n",
      "(19, 24)\n",
      "True\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "text = \"Customer ID: 4892, Order date: 2024-03-15\"\n",
    "m = re.search('Order', text)\n",
    "print(m.group())\n",
    "print(m.start())\n",
    "print(m.end())\n",
    "print(m.span())\n",
    "print(re.search('Invoice', text) is None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a245d84a",
   "metadata": {},
   "source": [
    "## Metacharacters\n",
    "\n",
    "Metacharacters are characters that carry special meaning inside a regex pattern: instead of matching themselves literally, they instruct the regex engine to do something specific, like match any character, mark a boundary, or repeat a pattern. There are 14 of them in Python's re module; the table below lists each bracket pair, `{}`, `[]`, and `()`, as one row. You need to escape them if you want them to be regular characters.\n",
    "\n",
    "| Type | Character | Meaning | Example |\n",
    "|---|---|---|---|\n",
    "| Wildcard | `.` | Matches any character except newline | `c.t` → cat, cot |\n",
    "| Anchor | `^` | Start of string | `^Hello` |\n",
    "| Anchor | `$` | End of string | `end$` |\n",
    "| Quantifier | `*` | 0 or more repetitions | `a*` |\n",
    "| Quantifier | `+` | 1 or more repetitions | `a+` |\n",
    "| Quantifier | `?` | Optional (0 or 1) / makes quantifier lazy | `colou?r` |\n",
    "| Quantifier | `{}` | Specific repetition range | `o{2}` |\n",
    "| Character Class Delimiters | `[]` | Defines a set of allowed characters | `[a-z]` |\n",
    "| Grouping Delimiters | `()` | Groups patterns and captures matches | `(cat\\|dog)` |\n",
    "| Escape | `\\` | Escapes metacharacters or forms special sequences | `\\d`, `\\w`, `\\.` |\n",
    "| Alternation | `\\|` | Logical OR between patterns | `cat\\|dog` |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-a245d84a",
   "metadata": {},
   "source": [
    "```{index} metacharacter, escaping metacharacters\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d07fdcb",
   "metadata": {},
   "source": [
    "To match a metacharacter literally, escape it with a backslash: `\\.` matches a real dot, and `\\$` matches a real dollar sign. Compare the patterns below:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "escape-demo",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['$', '$']\n",
      "['19.95', '19x95']\n",
      "['19.95']\n"
     ]
    }
   ],
   "source": [
    "text = \"Total: $19.95 (was $24.50)\"\n",
    "print(re.findall(r\"\\$\", text))                    # ['$', '$']: \\$ is a literal dollar sign\n",
    "\n",
    "print(re.findall(r\"19.95\", \"19.95 or 19x95\"))     # ['19.95', '19x95']: . matches any character\n",
    "print(re.findall(r\"19\\.95\", \"19.95 or 19x95\"))    # ['19.95']: \\. matches only a real dot"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "escape-next",
   "metadata": {},
   "source": [
    "The sections below present the metacharacters in groups."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dd02837e",
   "metadata": {},
   "source": [
    "### Character Classes\n",
    "\n",
    "Before writing larger patterns, it helps to know the core building blocks. **Character classes** match one character from a defined set. They're written with square brackets `[ ]`."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-dd02837e",
   "metadata": {},
   "source": [
    "```{index} character class, shorthand character class\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "60663719",
   "metadata": {},
   "source": [
    "| Pattern | Matches |\n",
    "| --- | --- |\n",
    "| `[aeiou]` | any single vowel |\n",
    "| `[a-z]` | any lowercase letter |\n",
    "| `[A-Z]` | any uppercase letter |\n",
    "| `[0-9]` | any digit |\n",
    "| `[a-zA-Z0-9]` | any alphanumeric character |\n",
    "| `[^aeiou]` | any character not a vowel (`^` negates) |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "230aa9bf",
   "metadata": {},
   "source": [
    "**Special sequences** are shorthand classes for common sets. They work on their own or inside brackets, as in `[\\d.]`, and each uppercase version matches every character the lowercase one does not:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d70de733",
   "metadata": {},
   "source": [
    "| Pattern | Meaning | Example Match |\n",
    "|---|---|---|\n",
    "| `\\d` | Unicode decimal digit | `7` |\n",
    "| `\\D` | Any character except a digit | `a`, `-` |\n",
    "| `\\w` | Unicode alphanumeric character or underscore | `A`, `é`, `9`, `_` |\n",
    "| `\\W` | Any character except a word character | `!`, space |\n",
    "| `\\s` | Unicode whitespace | space, tab, newline |\n",
    "| `\\S` | Any character except whitespace | `x`, `!` |\n",
    "\n",
    "`[0-9]` restricts a match to ASCII digits; `\\d` includes decimal digits from other writing systems. Likewise, `[a-z]` means lowercase ASCII letters, not every lowercase Unicode letter.\n",
    "\n",
    "The wildcard `.` is not a shorthand class: outside brackets it matches any character except newline, but inside brackets, as in `[.]`, it is a literal dot."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "44b5903b",
   "metadata": {},
   "source": [
    "Compare single-character matches below. The quantifiers introduced next will combine adjacent matches into runs."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "bbe068a5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd', '1', '2', '3', 'f', 'o', 'o', '_', 'b', 'a', 'r']\n",
      "['1', '2', '3']\n",
      "[' ', ' ', ' ']\n",
      "[' ', ' ', '!', ' ']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "s = 'Hello World 123! foo_bar'\n",
    "print(re.findall(r'\\w', s))  # one word character per match\n",
    "print(re.findall(r'\\d', s))  # individual decimal digits\n",
    "print(re.findall(r'\\s', s))  # whitespace characters\n",
    "print(re.findall(r'\\W', s))  # everything \\w does not match: spaces and !"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7a7268cf",
   "metadata": {},
   "source": [
    "`\\s` includes space, `\\n` (newline), `\\t` (tab), `\\r` (carriage return), `\\f` (form feed), `\\v` (vertical tab), and other Unicode whitespace. Use raw strings for regex patterns so Python preserves their backslashes."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6ce72136",
   "metadata": {},
   "source": [
    "### Quantifiers\n",
    "\n",
    "Quantifiers tell the regex engine how many times the preceding character, group, or character class should match.\n",
    "\n",
    "| Quantifier | Meaning | Example | Matches |\n",
    "|---|---|---|---|\n",
    "| `*` | **0 or more** | `ab*` | a, ab, abb, abbb |\n",
    "| `+` | **1 or more** | `ab+` | ab, abb, abbb (not a) |\n",
    "| `?` | **0 or 1** | `ab?` | a or ab only |\n",
    "| `{n}` | Exactly n | `o{2}` | oo |\n",
    "| `{n,}` | n or more | `o{2,}` | oo, ooo, oooo... |\n",
    "| `{n,m}` | Between n and m | `o{2,3}` | oo, ooo |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-6ce72136",
   "metadata": {},
   "source": [
    "```{index} quantifier\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "d6dfe973",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1', '2', '3']\n",
      "['123']\n",
      "['Hello', 'World', '123', 'foo_bar']\n",
      "['Hello', 'World']\n",
      "['123!', '_']\n",
      "['oo', 'oo']\n",
      "['oo', 'ooo']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "text = \"Hello World 123! foo_bar\"\n",
    "\n",
    "print(re.findall(r\"\\d\", text))        # individual digits\n",
    "print(re.findall(r\"\\d+\", text))       # consecutive digits\n",
    "print(re.findall(r\"\\w+\", text))       # words (incl. underscore)\n",
    "print(re.findall(r\"[A-Z][a-z]+\", text))  # capitalized words\n",
    "print(re.findall(r\"[^a-zA-Z\\s]+\", text)) # non-alpha, non-space\n",
    "\n",
    "# Exact and ranged quantifiers\n",
    "print(re.findall(r\"o{2}\", \"bot boot booot\"))     # ['oo', 'oo']\n",
    "print(re.findall(r\"o{2,3}\", \"bot boot booot\"))   # ['oo', 'ooo']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "16a6a5c6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['42', '09', '30', '2026', '03', '11']\n",
      "['User_', 'logged', 'in', 'at', 'on']\n",
      "['09:30']\n",
      "['2026-03-11']\n"
     ]
    }
   ],
   "source": [
    "sample = \"User_42 logged in at 09:30 on 2026-03-11\"\n",
    "\n",
    "print(re.findall(r'\\d+', sample))                  # all digit runs\n",
    "print(re.findall(r'[A-Za-z_]+', sample))            # word-like alphabetic tokens\n",
    "print(re.findall(r'\\d{2}:\\d{2}', sample))        # HH:MM time\n",
    "print(re.findall(r'\\d{4}-\\d{2}-\\d{2}', sample))  # YYYY-MM-DD date"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "bf8a0af3",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Regex Syntax Essentials\n",
    "# Difficulty: Basic\n",
    "# 1. Extract all uppercase letters\n",
    "# 2. Extract all digit sequences\n",
    "# 3. Extract letter+digit tokens like A12, B7, C999\n",
    "s = \"IDs: A12, B7, C999\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "30189825",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['I', 'D', 'A', 'B', 'C']\n",
      "['12', '7', '999']\n",
      "['A12', 'B7', 'C999']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "s = \"IDs: A12, B7, C999\"\n",
    "print(re.findall(r'[A-Z]', s))\n",
    "print(re.findall(r'\\d+', s))\n",
    "print(re.findall(r'[A-Z]\\d+', s))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "96205219",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Special Sequences and Escapes\n",
    "# Difficulty: Basic\n",
    "# 1. Extract all digit sequences\n",
    "# 2. Extract all word tokens\n",
    "# 3. Extract literal '$' and literal '.' matches\n",
    "s = \"Price: $19.95, code=A_7, spaces here\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "8b965a41",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['19', '95', '7']\n",
      "['Price', '19', '95', 'code', 'A_7', 'spaces', 'here']\n",
      "['$']\n",
      "['.']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "\n",
    "# Solution\n",
    "s = \"Price: $19.95, code=A_7, spaces here\"\n",
    "print(re.findall(r'\\d+', s))\n",
    "print(re.findall(r'\\w+', s))\n",
    "print(re.findall(r'\\$', s))\n",
    "print(re.findall(r'\\.', s))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "de7246f4",
   "metadata": {},
   "source": [
    "### Greedy vs. Non-greedy\n",
    "\n",
    "By default quantifiers are **greedy**: they match as much as possible. Add `?` after a quantifier to make it **non-greedy** (lazy)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-de7246f4",
   "metadata": {},
   "source": [
    "```{index} greedy matching, non-greedy matching\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "90c996be",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['<b>bold</b> and <i>italic</i>']\n",
      "['<b>', '</b>', '<i>', '</i>']\n"
     ]
    }
   ],
   "source": [
    "text = \"<b>bold</b> and <i>italic</i>\"\n",
    "\n",
    "# Greedy — matches as much as possible\n",
    "print(re.findall(r\"<.+>\", text))     # ['<b>bold</b> and <i>italic</i>']\n",
    "\n",
    "# Lazy — matches as little as possible\n",
    "print(re.findall(r\"<.+?>\", text))    # ['<b>', '</b>', '<i>', '</i>']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b76fbc8",
   "metadata": {},
   "source": [
    "In `<.+>`, the `+` is **greedy**. It matches as many characters as possible while still allowing the overall pattern to succeed. So it gobbles everything from the first `<` all the way to the last `>`.\n",
    "\n",
    "Adding `?` after a quantifier switches it to **lazy** mode: instead of matching as much as possible, it now matches **as little as possible**. So `<.+?>` still needs at least one character (that's the `+`), but stops at the earliest `>` it can find."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "33dbf4fd",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Greedy and Non-greedy Quantifiers\n",
    "# Difficulty: Basic\n",
    "# 1. Use the ? quantifier to find both spellings, 'color' and 'colour', in text.\n",
    "# 2. Extract the tags from html non-greedily: ['<x>', '</x>', '<x>', '</x>'].\n",
    "# 3. Run the same tag pattern greedily and compare the result.\n",
    "text = \"The color and the colour look the same.\"\n",
    "html = \"<x>1</x><x>2</x>\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "93c34729",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['color', 'colour']\n",
      "['<x>', '</x>', '<x>', '</x>']\n",
      "['<x>1</x><x>2</x>']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "text = \"The color and the colour look the same.\"\n",
    "html = \"<x>1</x><x>2</x>\"\n",
    "\n",
    "print(re.findall(r\"colou?r\", text))   # ['color', 'colour']\n",
    "print(re.findall(r\"<.*?>\", html))     # ['<x>', '</x>', '<x>', '</x>']\n",
    "print(re.findall(r\"<.*>\", html))      # ['<x>1</x><x>2</x>']: greedy grabs as much as it can"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e80681c",
   "metadata": {},
   "source": [
    "### Anchors\n",
    "\n",
    "Anchors don't match characters; they match positions in the string.\n",
    "\n",
    "| Anchor | Meaning |\n",
    "|---|---|\n",
    "| `^` | Start of string (or line with `re.MULTILINE`) |\n",
    "| `$` | End of string (or line) |\n",
    "| `\\b` | Word boundary |\n",
    "| `\\B` | Non-word boundary |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-3e80681c",
   "metadata": {},
   "source": [
    "```{index} anchor (regex), word boundary (\\b)\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "2b48b6ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Hello']\n",
      "['world']\n",
      "['cat']\n",
      "['cat', 'cat', 'cat']\n",
      "[]\n"
     ]
    }
   ],
   "source": [
    "# Anchors match positions, not characters.\n",
    "print(re.findall(r'^\\w+', 'Hello world'))  # ['Hello']\n",
    "print(re.findall(r'\\w+$', 'Hello world'))  # ['world']\n",
    "\n",
    "text = 'cat catfish concatenate'\n",
    "print(re.findall(r'\\bcat\\b', text))  # ['cat']: whole word\n",
    "print(re.findall(r'cat', text))        # three substring matches\n",
    "print(re.findall('\\bcat\\b', text))   # []: without r, Python turned each \\b into a backspace"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-anchor-boundaries",
   "metadata": {},
   "source": [
    "A word boundary is a transition between `\\w` and `\\W`, or a string edge next to a word character. Thus an underscore belongs to a regex word. The last line shows the raw-string problem from the start of this section: without `r`, the regex engine never sees `\\b`. By default, `^` applies to the start of the whole string; `$` also matches immediately before a final newline. Flags below show how line-by-line anchoring differs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "161e1a6b",
   "metadata": {},
   "source": [
    "### Groups and Capturing\n",
    "\n",
    "Parentheses `()` group part of a pattern into a single unit. A **capturing group** also saves the matched text so you can extract or reuse it afterward. Use **non-capturing groups** `(?:...)` when you need grouping for structure but don't need to extract the text. **Named groups** `(?P<name>...)` let you refer to captured text by name instead of number.\n",
    "\n",
    "| Syntax | Meaning |\n",
    "|---|---|\n",
    "| `(...)` | Capturing group |\n",
    "| `(?:...)` | Non-capturing group |\n",
    "| `(?P<name>...)` | Named group |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-161e1a6b",
   "metadata": {},
   "source": [
    "```{index} capturing group, non-capturing group (?:), named group\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-capture-shapes",
   "metadata": {},
   "source": [
    "The same date produces different return structures depending on the capturing groups. A non-capturing group still groups part of the pattern but adds no field: in the last line, changing the first group of the third pattern to `(?:...)` drops the year from the result."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "ch08-capture-shapes-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['2024-03']\n",
      "['2024']\n",
      "[('2024', '03')]\n",
      "['03']\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "text = '2024-03'\n",
    "print(re.findall(r'\\d{4}-\\d{2}', text))        # ['2024-03']\n",
    "print(re.findall(r'(\\d{4})-\\d{2}', text))      # ['2024']\n",
    "print(re.findall(r'(\\d{4})-(\\d{2})', text))    # [('2024', '03')]\n",
    "print(re.findall(r'(?:\\d{4})-(\\d{2})', text))  # ['03']\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-capture-feedback",
   "metadata": {},
   "source": [
    "With no capturing groups, `findall()` returns complete matches. One capturing group returns strings for that group; two or more return tuples in opening-parenthesis order. Predict the result if you remove only the second pair of parentheses from the third pattern, then run it: each result becomes a year string. This differs from a `Match` object's `.group(0)`, which always denotes the complete match."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7f845756",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('2024', '01', '15'), ('2023', '12', '31')]\n",
      "2024 01 15\n",
      "01/15/2024 and 12/31/2023\n"
     ]
    }
   ],
   "source": [
    "# Capturing groups\n",
    "dates = \"2024-01-15 and 2023-12-31\"\n",
    "print(re.findall(r\"(\\d{4})-(\\d{2})-(\\d{2})\", dates))\n",
    "# [('2024', '01', '15'), ('2023', '12', '31')]\n",
    "\n",
    "# Named groups: m is one object from the search, so gives only one match, not all matches\n",
    "m = re.search(r\"(?P<year>\\d{4})-(?P<month>\\d{2})-(?P<day>\\d{2})\", dates)\n",
    "print(m.group('year'), m.group('month'), m.group('day'))\n",
    "\n",
    "# Using groups in sub()\n",
    "print(re.sub(r\"(\\d{4})-(\\d{2})-(\\d{2})\", r\"\\2/\\3/\\1\", dates))\n",
    "# 01/15/2024 and 12/31/2023"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b006ebdc",
   "metadata": {},
   "source": [
    "In the `sub()` call above, the replacement `r\"\\2/\\3/\\1\"` uses **backreferences**: `\\1`, `\\2`, and `\\3` insert the text captured by groups 1, 2, and 3, so each date is rewritten in month/day/year order. Write the replacement as a raw string for the same reason as the pattern.\n",
    "\n",
    "On a `Match` object, `.group(1)`, `.group(2)`, and so on return individual groups, and `.group(0)` returns the full match. Named groups can make long patterns more readable."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "6e827051",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OrderID=4821; Customer=Alice; Total=$39.50\n",
      "4821\n",
      "Alice\n",
      "39.50\n"
     ]
    }
   ],
   "source": [
    "record = \"OrderID=4821; Customer=Alice; Total=$39.50\"\n",
    "pattern = r'OrderID=(\\d+); Customer=([A-Za-z]+); Total=\\$(\\d+(?:\\.\\d{2})?)'\n",
    "m = re.search(pattern, record)\n",
    "\n",
    "print(m.group(0))  # full match\n",
    "print(m.group(1))  # order id\n",
    "print(m.group(2))  # customer\n",
    "print(m.group(3))  # total amount"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "13f21af9",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Capture Groups\n",
    "# Difficulty: Intermediate\n",
    "# 1. Use one regex with 3 capture groups to extract name, age, dept\n",
    "# 2. Print each extracted value on its own line\n",
    "line = \"name=Bob,age=27,dept=Sales\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "2224328f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Bob\n",
      "27\n",
      "Sales\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "line = \"name=Bob,age=27,dept=Sales\"\n",
    "m = re.search(r'name=([A-Za-z]+),age=(\\d+),dept=([A-Za-z]+)', line)\n",
    "print(m.group(1))\n",
    "print(m.group(2))\n",
    "print(m.group(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cce69516",
   "metadata": {},
   "source": [
    "### Alternation (OR)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-cce69516",
   "metadata": {},
   "source": [
    "```{index} alternation (|)\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9a02878",
   "metadata": {},
   "source": [
    "Use `|` to match one of several alternatives. Alternation has the lowest precedence of any regex operator, so `cat|dog` means \"`cat` or `dog`\", and `\\.jpg|png` would mean \"`.jpg` or `png`\". Wrap the alternatives in a group, as in `\\.(jpg|png|gif)$`, to limit how far the `|` reaches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "c3e51f4a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['cat', 'dog']\n",
      "photo.jpg -> valid image file\n",
      "diagram.png -> valid image file\n",
      "animation.gif -> valid image file\n",
      "document.pdf -> not an image\n",
      "archive.zip -> not an image\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "print(re.findall(r\"cat|dog\", \"I have a cat and a dog\"))  # ['cat', 'dog']\n",
    "\n",
    "# pattern using alternation\n",
    "pattern = r\"\\.(jpg|png|gif)$\"\n",
    "\n",
    "files = [\n",
    "    \"photo.jpg\",\n",
    "    \"diagram.png\",\n",
    "    \"animation.gif\",\n",
    "    \"document.pdf\",\n",
    "    \"archive.zip\"\n",
    "]\n",
    "\n",
    "for file in files:\n",
    "    if re.search(pattern, file):\n",
    "        print(f\"{file} -> valid image file\")\n",
    "    else:\n",
    "        print(f\"{file} -> not an image\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "ff59c4e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found beverage: coffee\n",
      "Found beverage: tea\n",
      "No beverage found\n",
      "Found beverage: Coffee\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "\n",
    "pattern = r\"\\b(coffee|tea)\\b\"\n",
    "\n",
    "sentences = [\n",
    "    \"I like coffee in the morning.\",\n",
    "    \"She prefers tea at night.\",\n",
    "    \"He drinks water.\",\n",
    "    \"Coffee is my favorite.\"\n",
    "]\n",
    "\n",
    "for sentence in sentences:\n",
    "    match = re.search(pattern, sentence, re.IGNORECASE)\n",
    "\n",
    "    if match:\n",
    "        print(f\"Found beverage: {match.group()}\")\n",
    "    else:\n",
    "        print(\"No beverage found\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1c7e284",
   "metadata": {},
   "source": [
    "## Advanced Topics\n",
    "\n",
    "The patterns so far cover most everyday matching. This section adds three tools for harder cases: flags that change how a pattern matches, compiled patterns for reuse, and lookaround assertions that check the text around a match without including it."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ee22e3c",
   "metadata": {},
   "source": [
    "### Flags\n",
    "\n",
    "Flags change matching behavior:\n",
    "\n",
    "| Flag | Shorthand | Meaning |\n",
    "|---|---|---|\n",
    "| `re.IGNORECASE` | `re.I` | Case-insensitive matching |\n",
    "| `re.MULTILINE` | `re.M` | `^`/`$` match line start/end |\n",
    "| `re.DOTALL` | `re.S` | `.` matches newline too |\n",
    "| `re.VERBOSE` | `re.X` | Allow comments/whitespace in pattern |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-2ee22e3c",
   "metadata": {},
   "source": [
    "```{index} regex flags, re.IGNORECASE\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "4d3245a1",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Hello', 'HELLO', 'hello']\n",
      "['line1']\n",
      "['line1', 'line2', 'line3']\n",
      "[]\n",
      "['<div>\\nsome content\\n</div>']\n",
      "['hello@example.com', 'support@test.org']\n"
     ]
    }
   ],
   "source": [
    "# IGNORECASE\n",
    "print(re.findall(r'hello', 'Hello HELLO hello', flags=re.I))\n",
    "\n",
    "# MULTILINE changes the scope of ^ and $.\n",
    "multi = 'line1\\nline2\\nline3'\n",
    "print(re.findall(r'^\\w+', multi))\n",
    "print(re.findall(r'^\\w+', multi, flags=re.MULTILINE))\n",
    "\n",
    "# DOTALL lets the dot match newlines.\n",
    "text = '<div>\\nsome content\\n</div>'\n",
    "print(re.findall(r'<div>.*</div>', text))\n",
    "print(re.findall(r'<div>.*</div>', text, flags=re.DOTALL))\n",
    "\n",
    "# VERBOSE permits layout and comments outside character classes.\n",
    "email_pattern = r\"\"\"\n",
    "    [\\w.+-]+       # username\n",
    "    @              # at sign\n",
    "    [\\w-]+         # domain\n",
    "    \\.             # literal dot\n",
    "    [\\w.]+         # remaining domain text\n",
    "\"\"\"\n",
    "print(re.findall(email_pattern, 'Contact hello@example.com or support@test.org',\n",
    "                 flags=re.VERBOSE))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "453800d5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['ALICE@example.com', 'bob@Example.org']\n"
     ]
    }
   ],
   "source": [
    "text_block = \"\"\"Title: Notes\n",
    "Email: ALICE@example.com\n",
    "Email: bob@Example.org\"\"\"\n",
    "\n",
    "# IGNORECASE lets lowercase character classes match uppercase letters too\n",
    "emails = re.findall(r'[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}', text_block, flags=re.IGNORECASE)\n",
    "print(emails)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "f7afa4c2",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Regex Flags\n",
    "# Difficulty: Basic\n",
    "# 1. Use re.findall() with re.IGNORECASE | re.MULTILINE to\n",
    "#    extract every line that begins with 'error'\n",
    "# 2. Print the list of matches\n",
    "import re\n",
    "log = \"\"\"INFO: Server started\n",
    "error: disk full\n",
    "WARNING: low memory\n",
    "ERROR: connection lost\"\"\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "15265b18",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['error: disk full', 'ERROR: connection lost']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "log = \"\"\"INFO: Server started\n",
    "error: disk full\n",
    "WARNING: low memory\n",
    "ERROR: connection lost\"\"\"\n",
    "results = re.findall(r'^error.*$', log, flags=re.IGNORECASE | re.MULTILINE)\n",
    "print(results)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e898c620",
   "metadata": {},
   "source": [
    "### Compiled Patterns\n",
    "\n",
    "`pattern_object = re.compile(pattern, flags=0)` creates a reusable pattern object. Its methods take the text directly, for example `pattern_object.findall(text)`. This keeps the pattern and its flags together. The module functions cache recent patterns too, so compilation is chiefly an explicit organization and reuse choice, rather than a guarantee of a speedup.\n",
    "\n",
    "For validation, use `.fullmatch(text)`: `.match(text)` can accept a matching prefix while leaving trailing junk unchecked. These examples check simple formats, not whether an email address exists."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-e898c620",
   "metadata": {},
   "source": [
    "```{index} re.compile()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "1c2b8f29",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found: ['123-456-7890'] in 'Call me at 123-456-7890'\n",
      "Found: ['987.654.3210'] in 'My number is 987.654.3210'\n",
      "Found: ['555-123-4567', '800-999-0000'] in 'Reach us at 555-123-4567 or 800-999-0000'\n"
     ]
    }
   ],
   "source": [
    "# Compile once, use many times\n",
    "phone_pattern = re.compile(r\"\\b\\d{3}[-.]\\d{3}[-.]\\d{4}\\b\")\n",
    "\n",
    "texts = [\n",
    "    \"Call me at 123-456-7890\",\n",
    "    \"My number is 987.654.3210\",\n",
    "    \"No phone here\",\n",
    "    \"Reach us at 555-123-4567 or 800-999-0000\"\n",
    "]\n",
    "\n",
    "for t in texts:\n",
    "    matches = phone_pattern.findall(t)\n",
    "    if matches:\n",
    "        print(f\"Found: {matches} in '{t}'\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "2c84d8f4",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Compiled Patterns\n",
    "# Difficulty: Basic\n",
    "# 1. Compile a regex pattern that matches a simple email address\n",
    "# 2. Print each email with True or False using the compiled pattern's fullmatch() method\n",
    "import re\n",
    "emails = ['alice@example.com', 'not-an-email', 'bob@company.org', 'charlie_at_test.net']\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "d023474f",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "alice@example.com True\n",
      "not-an-email False\n",
      "bob@company.org True\n",
      "charlie_at_test.net False\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "emails = ['alice@example.com', 'not-an-email', 'bob@company.org', 'charlie_at_test.net']\n",
    "email_re = re.compile(r'[\\w.+-]+@[\\w-]+\\.[\\w.]+')\n",
    "for e in emails:\n",
    "    print(e, bool(email_re.fullmatch(e)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f90ad03b",
   "metadata": {},
   "source": [
    "### Lookahead and Lookbehind\n",
    "\n",
    "Match a pattern only if it is (or isn't) preceded/followed by another pattern, without including that other pattern in the match.\n",
    "\n",
    "| Syntax | Type | Meaning |\n",
    "|---|---|---|\n",
    "| `(?=...)` | Positive lookahead | Followed by |\n",
    "| `(?!...)` | Negative lookahead | NOT followed by |\n",
    "| `(?<=...)` | Positive lookbehind | Preceded by |\n",
    "| `(?<!...)` | Negative lookbehind | NOT preceded by |"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f90ad03b",
   "metadata": {},
   "source": [
    "```{index} lookahead, lookbehind, backtracking\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "c84820d8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['100', '300']\n",
      "['10', '200', '30']\n",
      "['200']\n",
      "['42.99', '5.00']\n"
     ]
    }
   ],
   "source": [
    "# Positive lookahead — prices followed by USD\n",
    "text = \"100USD 200EUR 300USD\"\n",
    "print(re.findall(r\"\\d+(?=USD)\", text))     # ['100', '300']\n",
    "\n",
    "# Negative lookahead — naive version backtracks into the numbers\n",
    "print(re.findall(r\"\\d+(?!USD)\", text))     # ['10', '200', '30']\n",
    "\n",
    "# Negative lookahead — also forbid a following digit\n",
    "print(re.findall(r\"\\d+(?!\\d|USD)\", text))  # ['200']\n",
    "\n",
    "# Positive lookbehind — extract amount after $\n",
    "text2 = \"Price: $42.99, discount: $5.00\"\n",
    "print(re.findall(r\"(?<=\\$)[\\d.]+\", text2)) # ['42.99', '5.00']"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-neg-lookahead-backtrack",
   "metadata": {},
   "source": [
    "The naive negative lookahead returns `'10'` and `'30'` because of **backtracking**. When `\\d+` first matches all of `100`, the lookahead sees `USD` and fails. The engine then gives back one digit and tries again with `10`. Now the next character is `0`, not `USD`, so the lookahead succeeds and the engine returns `'10'`, a fragment of a number that *is* followed by USD.\n",
    "\n",
    "The fix is to require that the number ends where the match ends. `(?!\\d|USD)` rejects a match that is followed by another digit or by `USD`, so the engine can no longer stop in the middle of a number. A word boundary such as `\\b\\d+\\b` does not help here: digits and letters are both word characters, so there is no boundary between `0` and `U` and that pattern would miss every amount. Excluding a following digit is the reliable choice for this text."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "60e69911",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Lookahead and Lookbehind\n",
    "# Difficulty: Intermediate\n",
    "# 1. Use a positive lookahead to extract all numbers followed by 'pts'\n",
    "# 2. Use a positive lookbehind to extract numbers preceded by 'scored '\n",
    "import re\n",
    "text = \"Alice scored 95pts, Bob scored 80pts, Charlie scored 73pts\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "c5ae44a4",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['95', '80', '73']\n",
      "['95', '80', '73']\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "text = \"Alice scored 95pts, Bob scored 80pts, Charlie scored 73pts\"\n",
    "print(re.findall(r'\\d+(?=pts)', text))        # positive lookahead\n",
    "print(re.findall(r'(?<=scored )\\d+', text))   # positive lookbehind"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b5861fdc",
   "metadata": {},
   "source": [
    "## Applications\n",
    "\n",
    "\n",
    "The rest of this section applies regular expressions to a real text, Bram Stoker's *Dracula*: first to clean the downloaded file, then to substitute text, and finally to validate input with `re.fullmatch()`. A quick reference table closes the section.\n",
    "\n",
    "### Cleaning Text\n",
    "\n",
    "```{index} text cleaning, Project Gutenberg\n",
    "```\n",
    "\n",
    "Before you can search the text of *Dracula*, you need to download it from Project Gutenberg and remove the header and footer information."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1afc4a3",
   "metadata": {},
   "source": [
    "The code below downloads the Dracula text from Project Gutenberg and saves it to the `data` folder. Then it cleans the file and saves the cleaned version in the same folder. All subsequent analysis will use these files."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-regex-file-prerequisite",
   "metadata": {},
   "source": [
    "File handling is developed in the {doc}`Files appendix <../appendices/packaging/0501-files>`. Here, `Path` combines the project data directory with each filename, `open(..., encoding='utf-8')` decodes text, and a `with` block closes both files even if an error occurs. The two loops in `clean_file` share one reader: the first consumes the header through the start marker; the second writes the body until the end marker."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "68b04060",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dracula already downloaded: /Users/tcn85/workspace/py/data/pg345.txt\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "from urllib.request import urlretrieve\n",
    "\n",
    "data_dir = project_root / 'data'\n",
    "data_dir.mkdir(parents=True, exist_ok=True)\n",
    "\n",
    "# Download Dracula text to the project data folder\n",
    "url = 'https://www.gutenberg.org/files/345/345-0.txt'\n",
    "raw_path = data_dir / 'pg345.txt'\n",
    "clean_path = data_dir / 'pg345_cleaned.txt'\n",
    "if not raw_path.exists():\n",
    "    urlretrieve(url, raw_path)\n",
    "    print('Downloaded Dracula to', raw_path)\n",
    "else:\n",
    "    print('Dracula already downloaded:', raw_path)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "id": "d759ef63",
   "metadata": {},
   "outputs": [],
   "source": [
    "def clean_file(input_file, output_file):\n",
    "    with open(input_file, encoding='utf-8') as reader, \\\n",
    "            open(output_file, 'w', encoding='utf-8') as writer:\n",
    "        for line in reader:\n",
    "            if is_special_line(line):\n",
    "                break\n",
    "        for line in reader:\n",
    "            if is_special_line(line):\n",
    "                break\n",
    "            writer.write(line)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "28577dec",
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_special_line(line):\n",
    "    \"\"\"Return True if the line marks the start or end of the Gutenberg content.\"\"\"\n",
    "    return line.startswith('***')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "id": "9f689533",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cleaned file saved to /Users/tcn85/workspace/py/data/pg345_cleaned.txt\n"
     ]
    }
   ],
   "source": [
    "# Clean the Dracula text and save to data/pg345_cleaned.txt\n",
    "clean_file(raw_path, clean_path)\n",
    "print('Cleaned file saved to', clean_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "521a7c5a",
   "metadata": {},
   "source": [
    "With the cleaned file saved, you can search it line by line. Here's a function that loops through the lines in the book until it finds one that matches the given pattern, and returns the `Match` object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "id": "dd3afac4",
   "metadata": {},
   "outputs": [],
   "source": [
    "def find_first(pattern, path=clean_path):\n",
    "    with open(path, encoding='utf8') as f:\n",
    "        for line in f:\n",
    "            result = re.search(pattern, line)\n",
    "            if result is not None:\n",
    "                return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "52b080be",
   "metadata": {},
   "source": [
    "You can use it to find the first mention of a character."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "a74228d0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'CHAPTER I. Jonathan Harker’s Journal\\n'"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = find_first('Harker')\n",
    "result.string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "565413cf",
   "metadata": {},
   "source": [
    "For this example, you didn't need a regular expression; the `in` operator would do the same thing. Regular expressions earn their keep when the pattern can vary.\n",
    "\n",
    "Suppose you want to find the first mention of Mina Murray in the book, but you are not sure whether the book refers to her by first name or last. Alternation (`|`, from the Alternation section) matches either name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "2d042bed",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'CHAPTER V. Letters—Lucy and Mina\\n'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pattern = 'Mina|Murray'\n",
    "result = find_first(pattern)\n",
    "result.string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b62fd404",
   "metadata": {},
   "source": [
    "A pattern can find a character's first or last name. The following function counts **matching lines**, adding at most one per line even if the pattern occurs twice. To count every occurrence instead, add `len(re.findall(pattern, line))` for each line."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "35dd291b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_matches(pattern, path=clean_path):\n",
    "    count = 0\n",
    "    with open(path, encoding='utf8') as f:\n",
    "        for line in f:\n",
    "            result = re.search(pattern, line)\n",
    "            if result is not None:\n",
    "                count += 1\n",
    "    return count"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "adaf5bb1",
   "metadata": {},
   "source": [
    "Next, count how many lines mention Mina by either name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "585882de",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "229"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "count_matches('Mina|Murray')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "81a35c6f",
   "metadata": {},
   "source": [
    "The `^` anchor from the Anchors section finds a line that starts with a given pattern."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "de17fdda",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Dracula, jumping to his feet, said:--\\n'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = find_first('^Dracula')\n",
    "result.string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c7cfb3f",
   "metadata": {},
   "source": [
    "And the `$` anchor finds a line that ends with a given pattern. Because `$` also matches just before a final newline, the newline at the end of each line does not get in the way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "b7dbd7ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'by five o’clock, we must start off; for it won’t do to leave Mrs. Harker\\n'"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = find_first('Harker$')\n",
    "result.string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "5f14fc19",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Search the Book\n",
    "# Difficulty: Intermediate\n",
    "# 1. Use find_first() with an anchor to find the first line that ends with 'blood'\n",
    "#    and print the line\n",
    "# 2. Use count_matches() with word boundaries to count the lines that contain\n",
    "#    the whole word 'blood' (so 'bloody' and 'bloodless' do not count)\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "92f55807",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "“We Szekelys have a right to be proud, for in our veins flows the blood\n",
      "\n",
      "107\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "print(find_first(r'blood$').string)\n",
    "print(count_matches(r'\\bblood\\b'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f67418ba",
   "metadata": {},
   "source": [
    "### String Substitution\n",
    "\n",
    "Bram Stoker was born in Ireland, and when *Dracula* was published in 1897, he was living in England.\n",
    "So you would expect him to use the British spelling of words like \"centre\" and \"colour\".\n",
    "To check, you can use the following pattern, which matches either \"centre\" or the American spelling \"center\"."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f67418ba",
   "metadata": {},
   "source": [
    "```{index} re.sub(), string substitution\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "a2557856",
   "metadata": {},
   "outputs": [],
   "source": [
    "pattern = 'cent(er|re)'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e197ea79",
   "metadata": {},
   "source": [
    "In this pattern, the parentheses enclose the part of the pattern the vertical bar applies to.\n",
    "So this pattern matches a sequence that starts with `'cent'` and ends with either `'er'` or `'re'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "9912bca3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'horseshoe of the Carpathians, as if it were the centre of some sort of\\n'"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = find_first(pattern)\n",
    "result.string"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "994b3902",
   "metadata": {},
   "source": [
    "As expected, he used the British spelling.\n",
    "\n",
    "You can also check whether he used the British spelling of \"colour\".\n",
    "The following pattern uses the `?` quantifier, so the `'u'` is optional."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "5648ad9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "pattern = 'colou?r'"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "64633322",
   "metadata": {},
   "source": [
    "This pattern matches either \"colour\" with the `'u'` or \"color\" without it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "2caa4b8c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'undergarment with long double apron, front, and back, of coloured stuff\\n'"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result = find_first(pattern)\n",
    "line = result.string\n",
    "line"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3dbb91ce",
   "metadata": {},
   "source": [
    "Again, as expected, he used the British spelling.\n",
    "\n",
    "Suppose you want to produce an edition of the book with American spellings.\n",
    "You can use the `sub` function in the `re` module, which does **string substitution**."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "c252a3b7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'undergarment with long double apron, front, and back, of colored stuff\\n'"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "re.sub(pattern, 'color', line)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2baef97d",
   "metadata": {},
   "source": [
    "The first argument is the pattern you want to find and replace, the second is what you want to replace it with, and the third is the string you want to search.\n",
    "In the result, you can see that \"colour\" has been replaced with \"color\".\n",
    "\n",
    "To find example lines like these, the `all_matches` function below prints every line that matches a pattern."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "35c380ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "def all_matches(pattern, path=clean_path):\n",
    "    \"\"\"Print every line in the file that matches pattern.\"\"\"\n",
    "    with open(path, encoding='utf8') as f:\n",
    "        for line in f:\n",
    "            result = re.search(pattern, line)\n",
    "            if result:\n",
    "                print(line.strip())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "53b797ca",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "weather. As I stood, the driver jumped again into his seat and shook the\n",
      "weatherworn, was still complete; but it was evidently many a day since\n",
      "it is a buoy with a bell, which swings in bad weather, and sends in a\n",
      "am awakened by her moving about the room. Fortunately, the weather is so\n",
      "learn the weather signs. To-day is a grey day, and the sun as I write is\n",
      "experienced here, with results both strange and unique. The weather had\n",
      "kept watch on weather signs from the East Cliff, foretold in an emphatic\n",
      "_22 July_.--Rough weather last three days, and all hands busy with\n",
      "weather. Passed Gibralter and out through Straits. All well.\n",
      "and entering on the Bay of Biscay with wild weather ahead, and yet last\n",
      "weather influences as we know that the Count can bring to bear; and if\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "that I am fully armed as there may be wolves; the weather is getting"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "all_matches('weather')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "656f4723",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: String Substitution\n",
    "# Difficulty: Intermediate\n",
    "# 1. Replace British spellings with American spellings using regex:\n",
    "#    colour -> color, centre -> center\n",
    "# 2. Print the transformed sentence\n",
    "sample = \"The colour of the city centre changed overnight.\"\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "ec5f54c7",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The color of the city center changed overnight.\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import re\n",
    "\n",
    "sample = \"The colour of the city centre changed overnight.\"\n",
    "sample = re.sub(r'colou?r', 'color', sample)\n",
    "sample = re.sub(r'cent(er|re)', 'center', sample)\n",
    "print(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fd5be89",
   "metadata": {},
   "source": [
    "### `re.fullmatch()` for Validation\n",
    "\n",
    "`re.fullmatch(pattern, text)` succeeds only if the **entire** string matches the pattern.\n",
    "This is the right tool for validation tasks (IDs, simple emails, phone formats, etc.)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-5fd5be89",
   "metadata": {},
   "source": [
    "```{index} re.fullmatch(), pattern validation\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "a50bff32",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EMP-0001 True\n",
      "EMP-12 False\n",
      "AEMP-0001 False\n",
      "EMP-12345 False\n"
     ]
    }
   ],
   "source": [
    "employee_id_pattern = r'EMP-\\d{4}'\n",
    "ids = ['EMP-0001', 'EMP-12', 'AEMP-0001', 'EMP-12345']\n",
    "\n",
    "for emp_id in ids:\n",
    "    print(emp_id, bool(re.fullmatch(employee_id_pattern, emp_id)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-validation-comparison",
   "metadata": {},
   "source": [
    "The same pattern can answer three different questions. `search()` allows text before and after the match, `match()` requires the match to begin at position zero, and `fullmatch()` requires the complete string to match. Predict the three results for each input before running this cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "ch08-validation-comparison-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "EMP-0001 True True True\n",
      "xEMP-0001 True False False\n",
      "EMP-0001junk True True False\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "pattern = r'EMP-[0-9]{4}'\n",
    "for value in ['EMP-0001', 'xEMP-0001', 'EMP-0001junk']:\n",
    "    print(value, bool(re.search(pattern, value)),\n",
    "          bool(re.match(pattern, value)), bool(re.fullmatch(pattern, value)))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch08-validation-feedback",
   "metadata": {},
   "source": [
    "The valid ID yields three true results. The leading `x` leaves only `search()` true. Trailing `junk` leaves both `search()` and `match()` true, which is why neither alone validates the entire ID. `[0-9]` expresses an ASCII-digit ID policy explicitly."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "4f4e253b",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Full String Validation\n",
    "# Difficulty: Intermediate\n",
    "# A valid course code must be: 2-4 uppercase letters, a dash, then 3 digits.\n",
    "# 1. Write the regex pattern\n",
    "# 2. Print each code with True/False using re.fullmatch\n",
    "codes = ['CS-101', 'MATH-240', 'CS101', 'EE-7']\n",
    "### Your code starts here\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "98b2b2e6",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CS-101 True\n",
      "MATH-240 True\n",
      "CS101 False\n",
      "EE-7 False\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "codes = ['CS-101', 'MATH-240', 'CS101', 'EE-7']\n",
    "pattern = r'[A-Z]{2,4}-\\d{3}'\n",
    "for code_str in codes:\n",
    "    print(code_str, bool(re.fullmatch(pattern, code_str)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62aa23e7",
   "metadata": {},
   "source": [
    "### Quick Reference\n",
    "\n",
    "**Characters**\n",
    "\n",
    "| Pattern | Meaning | Example match |\n",
    "|---|---|---|\n",
    "| `.` | Any character (except newline) | `c.t` → `cat`, `cot` |\n",
    "| `\\d` | Digit | `7` |\n",
    "| `\\w` | Word character (letter, digit, underscore) | `A`, `x`, `9`, `_` |\n",
    "| `\\s` | Whitespace (space, tab, newline) | ` ` |\n",
    "| `\\D`, `\\W`, `\\S` | Not a digit, word character, or whitespace | `-`, `!`, `x` |\n",
    "| `[abc]` | Character class: any one of `a`, `b`, `c` | `a` |\n",
    "| `[^abc]` | Negated class: any character except `a`, `b`, `c` | `d` |\n",
    "\n",
    "**Quantifiers**\n",
    "\n",
    "| Pattern | Meaning | Example |\n",
    "|---|---|---|\n",
    "| `*` | 0 or more | `ab*` → `a`, `ab`, `abb` |\n",
    "| `+` | 1 or more | `ab+` → `ab`, `abb` |\n",
    "| `?` | 0 or 1 (optional) | `colou?r` → `color`, `colour` |\n",
    "| `{n}` | Exactly n | `\\d{3}` → `123` |\n",
    "| `{n,}` | n or more | `\\d{2,}` → `12`, `12345` |\n",
    "| `{n,m}` | Between n and m | `\\d{2,4}` → `12`, `123` |\n",
    "| `*?` `+?` | Lazy (match as little as possible) | `<.+?>` |\n",
    "\n",
    "**Anchors**\n",
    "\n",
    "| Pattern | Meaning |\n",
    "|---|---|\n",
    "| `^` | Start of string (or line with `re.M`) |\n",
    "| `$` | End of string (or line) |\n",
    "| `\\b` | Word boundary |\n",
    "| `\\B` | Non-word boundary |\n",
    "\n",
    "**Groups**\n",
    "\n",
    "| Syntax | Meaning |\n",
    "|---|---|\n",
    "| `(...)` | Capturing group |\n",
    "| `(?:...)` | Non-capturing group |\n",
    "| `(?P<name>...)` | Named group |\n",
    "| `\\|` | Alternation (OR) |\n",
    "| `(?=...)` / `(?!...)` | Positive / negative lookahead |\n",
    "| `(?<=...)` / `(?<!...)` | Positive / negative lookbehind |\n",
    "\n",
    "**Flags**\n",
    "\n",
    "| Flag | Shorthand | Meaning |\n",
    "|---|---|---|\n",
    "| `re.IGNORECASE` | `re.I` | Case-insensitive matching |\n",
    "| `re.MULTILINE` | `re.M` | `^`/`$` match line start/end |\n",
    "| `re.DOTALL` | `re.S` | `.` matches newline too |\n",
    "| `re.VERBOSE` | `re.X` | Allow comments/whitespace in pattern |"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "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.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
