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

URL 매칭

~10 min · url, extraction

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

두 질문, 두 패턴

"URL 매칭" 이 사실 두 다른 질문:

  1. 이 전체 문자열이 URL? (검증)
  2. 이 텍스트의 URL 찾기. (추출)

다른 패턴, 다른 anchor.

검증 패턴

^https?://[\w-]+(\.[\w-]+)+(/[\w./?%&=+#-]*)?$

http 또는 https 받음, 점 하나 이상 도메인 필수, optional URL 글자 허용 경로.

추출 패턴

자유 텍스트에서 URL 찾기엔 더 permissive 하되 명백한 단어 경계에서 멈춤:

https?://[^\s)]+

http(s):// 다음 공백 또는 닫는 괄호 아닌 거. 닫는 괄호 멈춤이 (https://example.com) 같은 markdown URL 이 trailing ) 포함하는 거 막음.

Trailing 구두점 문제

문장 끝 URL 이 trailing 점, 콤마, 괄호 픽업. 해결책: 그것들 제외하는 negated class, OR 매칭 후 코드에서 trailing 구두점 strip.

정규식으로 URL 완전 검증 시도 X

진짜 URL 검증은 messy: 스킴 변형, IP 리터럴, 포트 번호, 국제화 도메인, fragment encoding. "이 URL 파싱되고 resolve?" 면 본인 언어 URL 라이브러리: Python urllib.parse.urlparse, JavaScript new URL(...), Go net/url.

Code

URL 패턴·python
import re

# 검증 (whole-string)
URL_VALID = re.compile(r'^https?://[\w-]+(\.[\w-]+)+(/[\w./?%&=+#-]*)?$')

bool(URL_VALID.fullmatch('https://example.com'))                # True
bool(URL_VALID.fullmatch('http://sub.domain.com/path?q=1'))     # True
bool(URL_VALID.fullmatch('not a url'))                          # False
bool(URL_VALID.fullmatch('ftp://example.com'))                  # False (http(s) 만)

# 추출 (텍스트에서 찾기)
URL_FIND = re.compile(r'https?://[^\s)]+')
re.findall(URL_FIND, 'see https://pippa.dev or https://cwk.io for more (https://other.org)')
# ['https://pippa.dev', 'https://cwk.io', 'https://other.org']

# Post-processing 에서 trailing 구두점 strip
import string
def clean_url(url):
    return url.rstrip(string.punctuation)

# 진짜 검증엔 — URL 라이브러리
from urllib.parse import urlparse
parsed = urlparse('https://sub.example.com:8080/path?q=1')
print(parsed.scheme)   # 'https'
print(parsed.netloc)   # 'sub.example.com:8080'
print(parsed.path)     # '/path'

External links

Exercise

본인 코드베이스에서 URL 감지/추출 자리 찾기. Audit: 정규식 사용? 검증 또는 추출? 검증이 URL 라이브러리 통과해야? 종종 답이 yes.

Progress

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

댓글 0

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

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