Skip to content

Commit aa24a1d

Browse files
[패턴과 플래그] 번역
1 parent fd495a1 commit aa24a1d

File tree

1 file changed

+64
-64
lines changed
  • 9-regular-expressions/01-regexp-introduction

1 file changed

+64
-64
lines changed
Lines changed: 64 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,161 +1,161 @@
11
# 패턴과 플래그
22

3-
Regular expressions are patterns that provide a powerful way to search and replace in text.
3+
정규 표현식(regular expression)은 문자 검색과 교체에 사용되는 패턴으로 강력한 기능을 제공합니다.
44

5-
In JavaScript, they are available via the [RegExp](mdn:js/RegExp) object, as well as being integrated in methods of strings.
5+
자바스크립트에선 [RegExp](mdn:js/RegExp) 객체와 문자열 메서드를 조합해 정규표현식을 사용할 수 있습니다.
66

77
## 정규 표현식
88

9-
정규 표현식("regexp" 또는 그냥 "reg"라고도 합니다)은 *패턴*과 선택적인 *플래그*로 구성됩니다
9+
정규 표현식('regexp' 또는 'reg'라고 줄여서 사용)은 *패턴(pattern)* 과 선택적으로 사용할 수 있는 *플래그(flag)* 로 구성됩니다.
1010

11-
정규식 객체는 두 가지 문법을 사용해 만들 수 있습니다.
11+
정규식 객체를 만들 땐 두 가지 문법이 사용됩니다.
1212

13-
긴 문법입니다.
13+
'긴' 문법은 다음과 같습니다.
1414

1515
```js
1616
regexp = new RegExp("pattern", "flags");
1717
```
1818

19-
그리고 짧게는, 슬래시 `"/"`를 사용합니다.
19+
'짧은' 문법은 슬래시(빗금) `"/"`를 사용합니다.
2020

2121
```js
22-
regexp = /pattern/; // 플래그 없음
23-
regexp = /pattern/gmi; // 플래그 g, m, i가 있는 경우 (곧 다룰 예정)
22+
regexp = /pattern/; // 플래그가 없음
23+
regexp = /pattern/gmi; // 플래그 g, m, i가 있음(각 플래그에 대해선 곧 다룰 예정)
2424
```
2525

26-
슬래시`"/"`자바스크립트에 정규 표현식을 생성하고 있다는 것을 알려줍니다. 문자열에 따옴표를 쓰는 것과 동일한 역할을 합니다.
26+
슬래시 `"/"`자바스크립트에게 정규 표현식을 생성하고 있다는 것을 알려줍니다. 문자열에 따옴표를 쓰는 것과 동일한 역할을 하죠.
2727

28-
In both cases `regexp` becomes an instance of the built-in `RegExp` class.
28+
짧은 문법을 사용하던 긴 문법을 사용하던 상관 없이 위 예시에서의 `regexp`는 내장 클래스 `RegExp`의 인스턴스가 됩니다.
2929

30-
The main difference between these two syntaxes is that pattern using slashes `/.../` does not allow for expressions to be inserted (like string template literals with `${...}`). They are fully static.
30+
두 문법의 중요한 차이점은 `/.../`를 사용하면 문자열 템플릿 리터럴에서 `${...}`를 사용했던 것처럼 중간에 표현식을 넣을 수 없다는 점입니다. 슬래시를 사용한 방법은 완전히 정적입니다.
3131

32-
Slashes are used when we know the regular expression at the code writing time -- and that's the most common situation. While `new RegExp`, is more often used when we need to create a regexp "on the fly" from a dynamically generated string. For instance:
32+
슬래시를 사용한 짧은 문법은 코드를 작성하는 시점에 패턴을 알고 있을 때 사용합니다. 아마 대다수가 이런 경우에 속할 겁니다. 반면 `new RegExp`를 사용한 긴 문법은 '상황에 따라' 동적으로 생성된 문자열을 가지고 정규 표현식을 만들어야 할 때 주로 사용합니다. 관련 예시를 살펴봅시다.
3333

3434
```js
35-
let tag = prompt("What tag do you want to find?", "h2");
35+
let tag = prompt("어떤 태그를 찾고 싶나요?", "h2");
3636

37-
let regexp = new RegExp(`<${tag}>`); // same as /<h2>/ if answered "h2" in the prompt above
37+
let regexp = new RegExp(`<${tag}>`); // 프롬프트에서 "h2"라고 대답한 경우, /<h2>/와 동일한 역할을 합니다.
3838
```
3939

4040
## 플래그
4141

42-
정규 표현식에는 검색에 영향을 주는 플래그가 있을 수 있습니다.
42+
정규 표현식엔 검색에 영향을 주는 플래그를 선택적으로 붙일 수 있습니다.
4343

44-
자바스크립트에는 딱 6개가 있습니다.
44+
자바스크립트는 6개의 플래그를 지원합니다.
4545

4646
`pattern:i`
47-
: 이 플래그를 사용하면 대·소문자 구분 없이 검색합니다. `A``a` 차이가 없습니다(아래 참조).
47+
: i 플래그가 붙으면 대·소문자 구분 없이 검색합니다. 따라서 `A``a` 차이가 없습니다(아래 예시 참조).
4848

4949
`pattern:g`
50-
: With this flag the search looks for all matches, without it -- only the first match is returned.
50+
: g 플래그가 붙으면 패턴과 일치하는 모든 것들을 찾습니다. g 플래그가 없으면 패턴과 일치하는 첫 번째 결과만 반환됩니다.
5151

5252
`pattern:m`
53-
: 다중 행 모드(<info:regexp-multiline-mode> 챕터 참조)
53+
: 다중 행 모드(multiline mode)를 활성화합니다. 자세한 내용은 <info:regexp-multiline-mode>에서 다룰 예정입니다.
5454

5555
`pattern:s`
56-
: "dotall" 모드를 활성화 시켜 `pattern:.` 문자가 개행 문자 `\n`도 포함하도록 합니다(<info:regexp-character-classes> 챕터 참조).
56+
: `pattern:.`개행 문자 `\n`도 포함하도록 'dotall' 모드를 활성화합니다. 자세한 내용은 <info:regexp-character-classes>에서 다룰 예정입니다.
5757

5858
`pattern:u`
59-
: 유니코드를 완벽하게 지원합니다. 이 플래그를 사용하면 surrogate pair를 올바르게 처리할 수 있습니다. 자세한 내용은 <info:regexp-unicode> 챕터를 참조하세요.
59+
: 유니코드 전체를 지원합니다. 이 플래그를 사용하면 서로게이트 쌍(surrogate pair)을 올바르게 처리할 수 있습니다. 자세한 내용은 <info:regexp-unicode>에서 다룰 예정입니다.
6060

6161
`pattern:y`
62-
: "Sticky" Mode: searching at the exact position in the text (<info:regexp-sticky> 챕터 참조)
62+
: 문자 내 특정 위치에서 검색을 진행하는 'sticky' 모드를 활성화 시킵니다. 자세한 내용은 <info:regexp-sticky>에서 다룰 예정입니다.
6363

6464
```smart header="색상"
65-
여기에서 색상 구성은 다음과 같습니다.
65+
정규 표현식을 설명할 때 사용되는 밑줄의 색상은 각각 다음과 같은 상징이 있습니다.
6666
6767
- 정규표현식 -- `pattern:빨강`
68-
- (검색할) 문자열 -- `subject:파랑`
69-
- 결과 -- `match:초록`
68+
- 검색할 문자열 -- `subject:파랑`
69+
- 검색 결과 -- `match:초록`
7070
```
7171

72-
## Searching: str.match
72+
## str.match로 검색하기
7373

74-
As mentioned previously, regular expressions are integrated with string methods.
74+
앞서 언급한 바와 같이 정규 표현식은 문자열 메서드와 조합하여 사용합니다.
7575

76-
The method `str.match(regexp)` finds all matches of `regexp` in the string `str`.
76+
`str.match(regexp)`를 호출하면 문자열 `str`에서 `regexp`와 일치하는 것들을 찾아내는 식으로 말이죠.
7777

78-
It has 3 working modes:
78+
`str.match`엔 세 가지 모드가 있습니다.
7979

80-
1. If the regular expression has flag `pattern:g`, it returns an array of all matches:
80+
1. 정규 표현식에 플래그 `pattern:g`가 붙으면 패턴과 일치하는 모든 것을 담은 배열을 반환합니다.
8181
```js run
8282
let str = "We will, we will rock you";
8383

84-
alert( str.match(/we/gi) ); // We,we (an array of 2 substrings that match)
84+
alert( str.match(/we/gi) ); // We,we (패턴과 일치하는 부분 문자열 두 개를 담은 배열)
8585
```
86-
Please note that both `match:We` and `match:we` are found, because flag `pattern:i` makes the regular expression case-insensitive.
86+
대·소문자 구분 없이 검색을 할 수 있도록 하는 플래그 `pattern:i`를 사용했기 때문에 `match:We``match:we` 모두가 반환되었습니다.
8787

88-
2. If there's no such flag it returns only the first match in the form of an array, with the full match at index `0` and some additional details in properties:
88+
2. 플래그 `pattern:g`가 붙지 않은 경우엔 패턴에 맞는 첫 번째 부분 문자열만 담은 배열을 반환합니다. 해당 문자열은 배열 인덱스 `0`에 저장되는데 이 문자열의 프로퍼티엔 상세한 추가 정보가 저장됩니다.
8989
```js run
9090
let str = "We will, we will rock you";
9191
92-
let result = str.match(/we/i); // without flag g
92+
let result = str.match(/we/i); // 플래그 g 없음
9393
94-
alert( result[0] ); // We (1st match)
94+
alert( result[0] ); // We (패턴에 일치하는 첫 번째 부분 문자열)
9595
alert( result.length ); // 1
9696
9797
// Details:
98-
alert( result.index ); // 0 (position of the match)
99-
alert( result.input ); // We will, we will rock you (source string)
98+
alert( result.index ); // 0 (부분 문자열의 위치)
99+
alert( result.input ); // We will, we will rock you (원본 문자열)
100100
```
101-
The array may have other indexes, besides `0` if a part of the regular expression is enclosed in parentheses. We'll cover that in the chapter <info:regexp-groups>.
101+
그런데 정규 표현식을 괄호로 둘러싼 경우엔 메서드 호출 시 반환되는 배열에 `0` 이외에도 다른 인덱스가 있을 수 있습니다. 자세한 내용은 <info:regexp-groups>에서 다루겠습니다.
102102

103-
3. And, finally, if there are no matches, `null` is returned (doesn't matter if there's flag `pattern:g` or not).
103+
3. 플래그 `pattern:g`의 유무와 상관없이 패턴과 일치하는 부분 문자열을 찾지 못한 경우엔 `null`이 반환됩니다.
104104

105-
This a very important nuance. If there are no matches, we don't receive an empty array, but instead receive `null`. Forgetting about that may lead to errors, e.g.:
105+
일치하는 부분 문자열이 없는 경우엔 빈 배열이 아닌 `null`을 반환한다는 점은 아주 중요한 차이점입니다. 이런 점을 잊고 코딩 하다 보면 다음과 같이 에러가 발생할 수 있습니다.
106106

107107
```js run
108-
let matches = "JavaScript".match(/HTML/); // = null
108+
let matches = "JavaScript".match(/HTML/); // matches엔 null이 저장됨
109109
110-
if (!matches.length) { // Error: Cannot read property 'length' of null
111-
alert("Error in the line above");
110+
if (!matches.length) { // TypeError: Cannot read property 'length' of null
111+
alert("바로 윗줄에서 에러가 발생합니다.");
112112
}
113113
```
114114

115-
If we'd like the result to always be an array, we can write it this way:
115+
`str.match` 호출 결과가 항상 배열이 되게 하려면 아래와 같은 방법을 사용하면 됩니다.
116116

117117
```js run
118118
let matches = "JavaScript".match(/HTML/)*!* || []*/!*;
119119
120120
if (!matches.length) {
121-
alert("No matches"); // now it works
121+
alert("정규 표현식과 일치하는 부분 문자열이 없습니다."); // 이제 에러없이 잘 동작하네요.
122122
}
123123
```
124124

125-
## Replacing: str.replace
125+
## str.replace로 치환하기
126126

127-
The method `str.replace(regexp, replacement)` replaces matches found using `regexp` in string `str` with `replacement` (all matches if there's flag `pattern:g`, otherwise, only the first one).
127+
메서드 `str.replace(regexp, replacement)`를 사용하면 `str` 내 부분 문자열 중 `regexp`에 일치하는 부분 문자열을 `replacement`로 교체할 수 있습니다. 이때 플래그 `pattern:g`가 있으면 모든 부분 문자열이 교체되고, 그렇지 않으면 첫 번째 부분 문자열만 교체됩니다.
128128

129-
For instance:
129+
예시:
130130

131131
```js run
132-
// no flag g
132+
// 플래그 g 없음
133133
alert( "We will, we will".replace(/we/i, "I") ); // I will, we will
134134
135-
// with flag g
135+
// 플래그 g 있음
136136
alert( "We will, we will".replace(/we/ig, "I") ); // I will, I will
137137
```
138138

139-
The second argument is the `replacement` string. We can use special character combinations in it to insert fragments of the match:
139+
여기서 두 번째 인수 `replacement`는 문자열인데, 문자열 안에 다음과 같은 특수 문자를 넣어주면 독특한 방식으로 문자열을 교체할 수 있습니다.
140140

141-
| Symbols | Action in the replacement string |
141+
| 특수 문자 | 교체 방식 |
142142
|--------|--------|
143-
|`$&`|inserts the whole match|
143+
|`$&`|패턴과 일치하는 부분 문자열|
144144
|<code>$&#096;</code>|inserts a part of the string before the match|
145145
|`$'`|inserts a part of the string after the match|
146146
|`$n`|if `n` is a 1-2 digit number, then it inserts the contents of n-th parentheses, more about it in the chapter <info:regexp-groups>|
147147
|`$<name>`|inserts the contents of the parentheses with the given `name`, more about it in the chapter <info:regexp-groups>|
148148
|`$$`|inserts character `$` |
149149

150-
An example with `pattern:$&`:
150+
`pattern:$&`를 사용한 예시를 살펴봅시다.
151151

152152
```js run
153153
alert( "I love HTML".replace(/HTML/, "$& and JavaScript") ); // I love HTML and JavaScript
154154
```
155155

156-
## Testing: regexp.test
156+
## regexp.test로 일치 여부 확인하기
157157

158-
The method `regexp.test(str)` looks for at least one match, if found, returns `true`, otherwise `false`.
158+
패턴과 일치하는 부분 문자열이 하나라도 있는 경우 메서드 `regexp.test(str)`을 호출하면 `true`가, 그렇지 않으면 `false`가 반환됩니다.
159159

160160
```js run
161161
let str = "I love JavaScript";
@@ -164,14 +164,14 @@ let regexp = /LOVE/i;
164164
alert( regexp.test(str) ); // true
165165
```
166166

167-
Later in this chapter we'll study more regular expressions, walk through more examples, and also meet other methods.
167+
지금까지 살펴본 내용은 기본에 불과합니다. 이제 이어지는 챕터들에선 더 많은 정규 표현식과 예시들, 메서드들을 살펴보도록 하겠습니다.
168168

169-
Full information about the methods is given in the article <info:regexp-methods>.
169+
메서드들에 대한 정보는 <info:regexp-methods>에서 확인할 수 있으니 참고 바랍니다.
170170

171-
## Summary
171+
## 요약
172172

173-
- A regular expression consists of a pattern and optional flags: `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`.
174-
- Without flags and special symbols (that we'll study later), the search by a regexp is the same as a substring search.
175-
- The method `str.match(regexp)` looks for matches: all of them if there's `pattern:g` flag, otherwise, only the first one.
176-
- The method `str.replace(regexp, replacement)` replaces matches found using `regexp` with `replacement`: all of them if there's `pattern:g` flag, otherwise only the first one.
177-
- The method `regexp.test(str)` returns `true` if there's at least one match, otherwise, it returns `false`.
173+
- 정규 표현식은 패턴과 선택적으로 사용할 수 있는 플래그 `pattern:g`, `pattern:i`, `pattern:m`, `pattern:u`, `pattern:s`, `pattern:y`로 구성됩니다.
174+
- 플래그와 특수 기호(추후 학습)가 없는 경우엔 일반적인 부분 문자열 검색과 동일한 방식으로 검색이 진행됩니다.
175+
- 플래그 `pattern:g`가 있는 경우엔 `str.match(regexp)`는 패턴과 일치하는 모든 부분 문자열을 검색합니다. `pattern:g`가 없는 경우엔 첫 번째 부분 문자열만 찾습니다.
176+
- `str.replace(regexp, replacement)``regexp`과 일치하는 부분 문자열을 `replacement`로 교체합니다. `pattern:g` 플래그가 있으면 부분 문자열 전체를, 없으면 첫 번째 부분 문자열을 교체합니다.
177+
- 패턴과 일치하는 부분 문자열이 하나라도 있는 경우 `regexp.test(str)``true`를 반환합니다. 그렇지 않으면 `false`가 반환됩니다.

0 commit comments

Comments
 (0)