정규식 기초 치트시트
정규식(regex)은 텍스트와 일치하는 패턴입니다. 각 기호를 토큰이라 하며 일치 동작을 바꿉니다. 아래 치트시트는 가장 자주 쓰는 토큰을 뜻과 복사해 시험할 수 있는 작은 예제와 함께 정리했습니다.
| 토큰 | 의미 | 예제 |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
참고
- 문자 집합 [ ] 안에서는 대부분의 토큰이 특수 의미를 잃습니다. 예를 들어 [ ] 안의 .은 그냥 점 하나와 일치합니다.
- 백슬래시(\)는 이스케이프 문자로, 특수 토큰을 문자 그대로 바꾸거나 그 반대도 됩니다.
- 엔진마다 다릅니다. Python, JavaScript, PCRE, Golang은 대부분의 토큰을 공유하지만 플래그와 look-around 지원은 다릅니다.
자주 묻는 질문
- 점(.)은 무엇과 일치하나요?
- 기본값으로 줄바꿈을 제외한 임의의 한 문자와 일치합니다. 그대로 점을 쓰려면 \. 처럼 이스케이프합니다.
- * 와 + 의 차이는?
- *는 앞 토큰에 0회 이상 일치하므로 'ab*'는 'a'도 매칭합니다. +는 1회 이상 필요해 'ab'는 되지만 'a'만으로는 안 됩니다.
- 숫자나 단어 문자는 어떻게 쓰나요?
- \d는 임의의 숫자(0-9), \w는 임의의 단어 문자(문자·숫자·밑줄)에 일치합니다. 반대는 \D와 \W입니다.
- ^ 와 $ 는 무엇인가요?
- ^는 문자열이나 행의 시작에, $는 끝에 일치를 고정합니다. ^pattern$을 함께 쓰면 문자열 전체 일치를 강제합니다.