C.W.K.
Stream
Lesson 07 of 12 · published

Markdown 패턴

~10 min · markdown, rewriting

Level 0패턴 호기심
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Markdown 이 줄 지향, 부분적 정규식 친화

Markdown 의 inline 패턴 (**bold**, *italic*, `code`, [link](url)) 가 정규식과 잘 매칭. 블록 패턴 (리스트, blockquote, code fence) 가 줄별 state. 진짜 Markdown 파서가 다 정확 처리.

Bold 와 italic

Bold:    \*\*([^*]+)\*\*
Italic:  \*([^*]+)\*

순서 주의 — bold 먼저 처리하면 italic 패턴이 우연히 ** 소비 X.

Inline 코드

`([^`]+)`

비-backtick 콘텐츠 둘러싼 backtick. Backtick 포함 코드는 진짜 Markdown 이 double backtick (``code with `backticks` inside``) 사용 — 필요시 처리.

링크

\[([^\]]+)\]\(([^)]+)\)

그룹 1 에 링크 텍스트, 그룹 2 에 URL. 중첩 대괄호 또는 이미지 (![alt](url)) 처리 X — 시작에 !? 추가하면 됨.

Heading

줄 anchor: ^(#{1,6})\s+(.+?)\s*$ + MULTILINE. 그룹 1 에 레벨 (# 개수), 그룹 2 에 텍스트.

옳은 도구: 진짜 파서

Markdown 을 HTML 로 변환, 중첩 리스트 처리, 또는 ad-hoc 재작성 넘는 뭐든: 진짜 파서. Python markdown 또는 mistune, JS marked, Rust pulldown-cmark. 정규식이 spot 수정과 가벼운 변환용.

Code

Markdown 재작성·python
import re

text = '''# Title
This is **bold** and *italic* and `code`.
See [the docs](https://example.com).'''

# Bold 를 HTML 로
text = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', text)

# Italic — 주의: bold 후에 돌아야 bold 일부 매칭 X
text = re.sub(r'(?<!\*)\*([^*]+)\*(?!\*)', r'<em>\1</em>', text)

# Inline 코드
text = re.sub(r'`([^`]+)`', r'<code>\1</code>', text)

# 링크
text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)

# Heading (멀티라인)
def heading(m):
    level = len(m.group(1))
    return f'<h{level}>{m.group(2)}</h{level}>'

text = re.sub(r'^(#{1,6})\s+(.+?)\s*$', heading, text, flags=re.MULTILINE)

print(text)
# <h1>Title</h1>
# This is <strong>bold</strong> and <em>italic</em> and <code>code</code>.
# See <a href="https://example.com">the docs</a>.

External links

Exercise

Markdown 파일. 모든 링크 [text](url) 찾고 두 컬럼에 링크 텍스트와 URL print 하는 정규식 작성. 진짜 문서에 돌리기. 풀 Markdown semantic 필요 없을 때 정규식이 inline 패턴 얼마나 깨끗히 처리하는지 인지.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.