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

Alternation — | 연산자

~8 min · alternation, or

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

이거 OR 저거 매칭

파이프 글자 | 는 OR. cat|dog 는 부분 문자열 'cat' 또는 'dog' 매칭. 엔진이 왼쪽에서 오른쪽으로 각 대안 시도; 첫 매칭 win.

순서 중요

대부분 정규식 엔진은 longest-match 아님 — first-match. 패턴 cat|cats 입력 'cats' 는 'cat' 만 매칭, 그게 먼저 시도되니까. 더 긴 거 매칭하려면 먼저: cats|cat.

이건 awk 의 POSIX longest-match 동작과 반대. 본인이 쓸 대부분 엔진 (Python, JS, PCRE) 은 first-match.

항상 alternation 그룹

괄호 없으면 alternation 이 양쪽으로 가능한 만큼 확장. 패턴 cat|dog 만이면 OK. 하지만 my cat|dog 는 "my cat" 또는 "dog" 의미 — "my (cat or dog)" 아님. 후자면 wrap: my (?:cat|dog).

이게 입문 정규식 #1 alternation 버그.

성능: alternation 비쌈

엔진이 모든 위치에 모든 대안 시도. 긴 리스트는 character class 가 극적으로 빠름: [abcde](?:a|b|c|d|e) 이김. 클래스에 안 맞는 멀티 글자 대안에 alternation 사용.

Code

Alternation 패턴·python
import re

# 단순 OR
re.findall(r'cat|dog', 'I have a cat and a dog')
# ['cat', 'dog']

# First-match 승 — 함정
re.search(r'cat|cats', 'cats').group()
# 'cat'  — 'cats' 아님!
re.search(r'cats|cat', 'cats').group()
# 'cats'  — 순서 중요

# 버그: alternation 이 생각보다 더 먹음
re.findall(r'my cat|dog', 'my cat my dog')
# ['my cat', 'dog']  — 두 번째는 그냥 'dog' ('my' 없음)

# 수정: alternation 그룹화
re.findall(r'my (?:cat|dog)', 'my cat my dog')
# ['my cat', 'my dog']

# Character class 가 짧은 alternation 이김
# 같은 일
re.findall(r'[aeiou]', 'hello')      # ['e', 'o']
re.findall(r'a|e|i|o|u', 'hello')    # ['e', 'o']  — 더 느리고 노이지

External links

Exercise

줄 시작에서 다음 인사말 매칭하는 패턴: 'hi', 'hello', 'hey', 'hola'. 순서 중요? 'hello there' 매칭 시도 — 패턴이 'hello' 잡나 'hi' 잡나? 필요하면 순서 조정.

Progress

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

댓글 0

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

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