Skip to content

Commit 61bbec5

Browse files
committed
feat(day 164): parse Markdown inline code blocks into HTML <code> tags
1 parent e3fd65b commit 61bbec5

1 file changed

Lines changed: 64 additions & 0 deletions

File tree

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
"""
2+
3+
Markdown Inline Code Parser
4+
Given a string of Markdown that includes one or more inline code blocks, return the equivalent HTML string.
5+
6+
Inline code blocks in Markdown use a single backtick (`) at the start and end of the code block text.
7+
8+
Return the given string with all code blocks converted to HTML code tags.
9+
10+
For example, given the string "Use `let` to declare the variable.", return "Use <code>let</code> to declare the variable.".
11+
12+
Note: The console may not display HTML tags in strings when logging messages. Check the browser console to see logs with tags included.
13+
"""
14+
15+
import unittest
16+
17+
class MarkdownInlineCodeParserTest(unittest.TestCase):
18+
19+
def test1(self):
20+
self.assertEqual(parse_inline_code("Use `let` to declare the variable."), "Use <code>let</code> to declare the variable.")
21+
22+
def test2(self):
23+
self.assertEqual(parse_inline_code("Use `let` or `const` to declare a variable."), "Use <code>let</code> or <code>const</code> to declare a variable.")
24+
25+
def test3(self):
26+
self.assertEqual(parse_inline_code("Run `npm install` then `npm start`."), "Run <code>npm install</code> then <code>npm start</code>.")
27+
28+
29+
30+
31+
32+
import re
33+
def parse_inline_code(markdown):
34+
35+
markdown = re.sub(r'`(.+?)`',r"<code>\1</code>", markdown)
36+
37+
return markdown
38+
39+
40+
41+
"""
42+
1. The regex handles multiple inline code blocks in the same string because because re.sub applies globally.
43+
2. Empty code block
44+
if someone writes ``````(two bacticks with nothing inside), the regex won't match becuase .+? requires at least one character.
45+
-> Fix: use .*? instead of .+? if you want to allow empty inline code.
46+
47+
re.sub(r'`(.*?`)', r"<code>\1</code>", markdown)
48+
49+
3. Escaped backticks or nested cases
50+
Markdown doesn't allow nesting inline code with backtics, but if you had something like ``Use `backtick``` your regex would still
51+
try to match. Handling escapes would require more complex parsing, but for most cases the above solution is fine.
52+
The only change is using (.*?) instead of (.+?)
53+
otherwise the solution is solid and efficient
54+
"""
55+
def markdown_inline_code(markdown):
56+
57+
return re.sub(r'`([^`]+)`', r'<code>\1</code>', markdown)
58+
59+
60+
61+
62+
if __name__ == "__main__":
63+
print(parse_inline_code("Use `let` to declare the variable."))
64+
unittest.main()

0 commit comments

Comments
 (0)