C.W.K.
Stream
Lesson 03 of 10 · published

Negative Lookahead — (?!...)

~8 min · lookahead, negative

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

뭔가 NOT 따라옴 주장

(?!...) 는 inverse: "이 위치에서 안의 패턴이 NOT 매칭." 같은 zero-width 동작 — 글자 소비 없음. 매칭은 lookahead 패턴이 실패할 때만 성공.

흔한 패턴

특정 suffix 따라올 때 빼고 단어 매칭. cat(?!s) 가 'cat' 매칭하지만 'cats' 안 함 — negative lookahead 가 's' 안 옴 주장.

stop word 따라오지 않는 토큰 찾기. 파싱에서 "예약어 따라올 때 빼고 어떤 단어든" 원할 때 유용.

URL 감지의 false positive 회피. http(?!s://) 가 'http' 매칭하지만 'https://' 안 함 — 평범한 HTTP 참조 업그레이드하지만 이미 보안된 거 스킵하고 싶을 때.

멘탈 flip

입문자 대부분이 negative lookahead 어려워하는 건 질문 뒤집어야 하니까. "뭐가 매칭해야 하지?" 대신 "다음 거가 NOT 뭐여야 하지?" 로 묻기. 연습이 도움; 가장 깨끗한 패턴은 종종 메인 매칭에 positive 묘사 + 한 특정 케이스 제외하는 negative lookahead.

Code

Negative lookahead 패턴·python
import re

# 'cat' 인데 'cats' 아님
re.findall(r'\bcat(?!s)\b', 'cats and a cat scatter')
# ['cat']  — 단독 'cat' 만

# 평범한 'http' 인데 'https://' 아님
re.findall(r'http(?!s://)', 'http://a.com https://b.com httpd')
# ['http', 'http']  — 첫 http 와 httpd 안의 'http'

# 'rd' 안 따라오는 숫자 (그래서 '3rd' 아님)
re.findall(r'\b\d+(?!rd\b)', '1st 2nd 3rd 4th 7 11')
# ['1', '2', '4', '7', '11']  — '3' 제외, 'rd' 따라오니까

# 'ing' 안 따라오는 단어
re.findall(r'\b\w+(?!ing)\b', 'run running jump jumping read')
# 주의: \w+ 가 greedy 니까 까다로움 — 패턴 조정 필요

External links

Exercise

단어 'test' 가 'testing', 'tested', 'tests' 일부 아닐 때 찾는 정규식. test the testing tested tests 테스트. 단독 'test' 만 매칭되어야.

Progress

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

댓글 0

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

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