Back
+30 XP
Concept

Markdown Bold & Italic Inline Lexer

Building lightweight documentation tools requires converting inline formatting markers into semantic HTML. Order of operations is crucial: multi-character tokens like `**bold**` and `__bold__` (`<strong>`) must be parsed before single-character tokens like `*italic*` and `_italic_` (`<em>`) 🖋️📜⚡.

python
import re

BOLD_RE = re.compile(r"(\*\*|__)(.+?)\1")
ITALIC_RE = re.compile(r"(\*|_)(.+?)\1")

def lex_inline(text):
    text = BOLD_RE.sub(r"<strong>\2</strong>", text)
    return ITALIC_RE.sub(r"<em>\2</em>", text)

raw = "Check **this bold** and *this italic* out."
print("HTML Result:", lex_inline(raw))

# 3. Markdown Bold & Italic Inline Lexer Every modern developer tool—from chat apps to static site generators—features a lightweight markdown renderer. While full CommonMark parsers construct complete abstract syntax trees, inline string tokenizers handle high-speed in-memory rendering 🛑. ```python # Delimiter Precedence Problem: # Target String: "**Bold Text**" # If Italic runs first: *(*Bold Text*)* -> <em>*Bold Text</em>* (Broken!) # If Bold runs first: **Bold Text** -> <strong>Bold Text</strong> (Correct!) ``` ### Lexer Construction Invariants 1. **Longest Match First**: Always scan and replace multi-character tokens (`**`, `__`, `~~`) before checking single-character tokens (`*`, `_`). 2. **Non-Greedy Quantifiers (`+?`)**: Greedy matching `(.*)` would consume everything between the very first marker in a paragraph and the last marker, ruining multiple formatting spans on the same line. 3. **Whitespace Boundary Lookaround**: Enforce that markers touch non-whitespace characters (`(?=\S)` and `(?<=\S)`) so ordinary math formulas like `4 * 5 * 6` are not mistakenly parsed as italics 🖋️📜⚡. --- ### Interactive Pop-Quiz 🧠 #### What happens if a markdown lexer processes single-asterisk italic (`*`) before double-asterisk bold (`**`)? - [ ] The outer asterisks are partially matched as italics, leaving stray inner asterisks and corrupting the bold syntax 🛑 - [ ] The regex compiler crashes with a buffer overflow - [ ] Python transforms the string into binary bytes - [ ] The string is printed upside down in the terminal --- ### Practical Challenge 🎯 Implement `parse_markdown_inline(text: str) -> str` using regular expressions. First replace bold syntax (`**...**` and `__...__`) with `<strong>...</strong>`, then replace italic syntax (`*...*` and `_..._`) with `<em>...</em>`. Test with `'This is **very bold** and this is *subtle italic* and __strong__ with _emphasis_.'`. Assert that expected tags are produced and print the output. <details> <summary>Solution</summary> ```python import re BOLD_RE = re.compile(r"(\*\*|__)(?=\S)(.+?)(?<=\S)\1") ITALIC_RE = re.compile(r"(\*|_)(?=\S)(.+?)(?<=\S)\1") def parse_markdown_inline(text: str) -> str: # Bold must precede italic to prevent eating the first asterisk of ** res = BOLD_RE.sub(r"<strong>\2</strong>", text) res = ITALIC_RE.sub(r"<em>\2</em>", res) return res sample = "This is **very bold** and this is *subtle italic* and __strong__ with _emphasis_." converted = parse_markdown_inline(sample) assert "<strong>very bold</strong>" in converted assert "<em>subtle italic</em>" in converted assert "<strong>strong</strong>" in converted assert "<em>emphasis</em>" in converted print(f"Inline Lexer verified: {converted}") ``` </details>

Checkpoint

What happens if a markdown lexer processes single-asterisk italic (`*`) before double-asterisk bold (`**`)? 🧠

Practice

Implement `parse_markdown_inline(text: str) -> str` using regular expressions. First replace bold syntax (`**...**` and `__...__`) with `<strong>...</strong>`, then replace italic syntax (`*...*` and `_..._`) with `<em>...</em>`. Test with `'This is **very bold** and this is *subtle italic* and __strong__ with _emphasis_.'`. Assert that expected tags are produced and print the output. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks