diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:42:17 -0500 |
commit | da78a9e329e272dedb2400b79a3bdeebff387d47 (patch) | |
tree | e6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/ko/web/javascript/reference/global_objects/regexp | |
parent | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff) | |
download | translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2 translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip |
initial commit
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/regexp')
5 files changed, 730 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html new file mode 100644 index 0000000000..4659688c51 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/exec/index.html @@ -0,0 +1,188 @@ +--- +title: RegExp.prototype.exec() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec +--- +<div>{{JSRef}}</div> + +<p><strong><code>exec()</code></strong> 메서드는 주어진 문자열에서 일치 탐색을 수행한 결과를 배열 혹은 {{jsxref("null")}}로 반환합니다.</p> + +<p>JavaScript {{jsxref("RegExp")}} 객체는 {{jsxref("RegExp.global", "global")}} 또는 {{jsxref("RegExp.sticky", "sticky")}} 플래그를 설정(<code>/foo/g</code>, <code>/foo/y</code> 등)한 경우 이전 일치의 인덱스를 저장하므로 <strong>상태를 가지고</strong>(stateful) 있습니다. 이를 내부적으로 사용하여, {{jsxref("String.prototype.match()")}}와는 다르게 (캡처 그룹을 포함한) 문자열 내의 일치 다수를 반복해 순회할 수 있습니다.</p> + +<p>(캡처 그룹을 포함한) 문자열 내의 다수 일치를 수행할 수 있는 보다 간편한 신규 메서드, {{jsxref("String.prototype.matchAll()")}}이 제안된 상태입니다.</p> + +<p>단순히 <code>true</code>/<code>false</code>가 필요한 경우 {{jsxref("RegExp.prototype.text()")}} 메서드 혹은 {{jsxref("String.prototype.search()")}}를 사용하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>regexObj</var>.exec(<var>str</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code>str</code></dt> + <dd>정규 표현식 검색을 수행할 대상 문자열.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>정규 표현식이 일치하면, <code>exec()</code> 메서드는 배열(추가 속성 <code>index</code>와 <code>input</code> 포함, 아래 설명을 참고하세요)을 반환하고, 정규 표현식 객체의 {{jsxref("RegExp.lastIndex", "lastIndex")}} 속성을 업데이트합니다. 반환하는 배열은 일치한 텍스트를 첫 번째 원소로, 각각의 괄호 캡처 그룹을 이후 원소로 포함합니다.</p> + +<p>정규표현식 검색에 실패하면, <code>exec()</code> 메서드는 {{jsxref("null")}}을 반환하고 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 <code>0</code>으로 설정합니다.</p> + +<h2 id="설명">설명</h2> + +<p>다음과 같은 예제를 고려해보세요.</p> + +<pre class="brush: js notranslate">// Match "quick brown" followed by "jumps", ignoring characters in between +// Remember "brown" and "jumps" +// Ignore case +let re = /quick\s(brown).+?(jumps)/ig; +let result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');</pre> + +<p>다음의 표는 이 스크립트의 결과에 대해 보여줍니다.</p> + +<table class="fullwidth-table standard-table"> + <thead> + <tr> + <th scope="row">객체</th> + <th scope="col">속성/인덱스</th> + <th scope="col">설명</th> + <th scope="col">예제</th> + </tr> + </thead> + <tbody> + <tr> + <th colspan="1" rowspan="4" scope="row" style="vertical-align: top;"><code>result</code></th> + <td><code>[0]</code></td> + <td>일치한 전체 문자.</td> + <td><code>"Quick Brown Fox Jumps"</code></td> + </tr> + <tr> + <td><code>[1], ...[<var>n</var>]</code></td> + <td> + <p>(존재하는 경우) 괄호로 감싼 부분문자열.</p> + + <p>괄호로 감싼 부분문자열 숫자의 제한은 없습니다.</p> + </td> + <td> + <p><code>result[1] === "Brown"</code></p> + + <p><code>result[2] === "Jumps"</code></p> + </td> + </tr> + <tr> + <td><code>index</code></td> + <td>일치가 문자열에서 위치하는 인덱스. (0 시작)</td> + <td><code>4</code></td> + </tr> + <tr> + <td><code>input</code></td> + <td>원본 문자열.</td> + <td><code>"The Quick Brown Fox Jumps Over The Lazy Dog"</code></td> + </tr> + <tr> + <th colspan="1" rowspan="5" scope="row" style="vertical-align: top;"><code>re</code></th> + <td><code>lastIndex</code></td> + <td> + <p>다음 일치를 시작할 인덱스.</p> + + <p><code>g</code>를 누락하면 항상 <code>0</code>입니다.</p> + </td> + <td><code>25</code></td> + </tr> + <tr> + <td><code>ignoreCase</code></td> + <td><code>i</code> 플래그로 대소문자를 무시했는지 여부.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>global</code></td> + <td><code>g</code> 플래그로 전역 일치를 수행하는지 여부.</td> + <td><code>true</code></td> + </tr> + <tr> + <td><code>multiline</code></td> + <td><code>m</code> 플래그로 여러 줄에 걸친 탐색을 수행하는지 여부.</td> + <td><code>false</code></td> + </tr> + <tr> + <td><code>source</code></td> + <td>패턴 문자열.</td> + <td><code>"quick\s(brown).+?(jumps)"</code></td> + </tr> + </tbody> +</table> + +<h2 id="예제">예제</h2> + +<h3 id="Finding_successive_matches">Finding successive matches</h3> + +<p>If your regular expression uses the "<code>g</code>" flag, you can use the <code>exec()</code> method multiple times to find successive matches in the same string. When you do so, the search starts at the substring of <code>str</code> specified by the regular expression's {{jsxref("RegExp.lastIndex", "lastIndex")}} property ({{jsxref("RegExp.prototype.test()", "test()")}} will also advance the {{jsxref("RegExp.lastIndex", "lastIndex")}} property). For example, assume you have this script:</p> + +<pre class="brush: js notranslate">var myRe = /ab*/g; +var str = 'abbcdefabh'; +var myArray; +while ((myArray = myRe.exec(str)) !== null) { + var msg = 'Found ' + myArray[0] + '. '; + msg += 'Next match starts at ' + myRe.lastIndex; + console.log(msg); +} +</pre> + +<p>This script displays the following text:</p> + +<pre class="notranslate">Found abb. Next match starts at 3 +Found ab. Next match starts at 9 +</pre> + +<p>Note: Do not place the regular expression literal (or {{jsxref("RegExp")}} constructor) within the <code>while</code> condition or it will create an infinite loop if there is a match due to the {{jsxref("RegExp.lastIndex", "lastIndex")}} property being reset upon each iteration. Also be sure that the global flag is set or a loop will occur here also.</p> + +<h3 id="Using_exec_with_RegExp_literals">Using <code>exec()</code> with <code>RegExp</code> literals</h3> + +<p>You can also use <code>exec()</code> without creating a {{jsxref("RegExp")}} object:</p> + +<pre class="brush: js notranslate">var matches = /(hello \S+)/.exec('This is a hello world!'); +console.log(matches[1]); +</pre> + +<p>This will log a message containing 'hello world!'.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.exec")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">Regular Expressions</a> chapter in the <a href="/en-US/docs/Web/JavaScript/Guide">JavaScript Guide</a></li> + <li>{{jsxref("RegExp")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..541d3585db --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,233 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +<div>{{JSRef}}</div> + +<p><strong><code>RegExp</code></strong> 생성자는 패턴을 사용해 텍스트를 판별할 때 사용합니다.</p> + +<p>정규 표현식에 대한 소개는 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a>을 참고하세요.</p> + +<h2 id="설명">설명</h2> + +<h3 id="리터럴_표기법과_생성자">리터럴 표기법과 생성자</h3> + +<p><code>RegExp</code> 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.</p> + +<ul> + <li><strong>리터럴 표기법</strong>의 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않습니다.</li> + <li><strong>생성자 함수</strong>의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.</li> +</ul> + +<p>다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">/ab+c/i +new RegExp(/ab+c/, 'i') // 리터럴 +new RegExp('ab+c', 'i') // 생성자 +</pre> + +<p>리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.</p> + +<p>정규 표현식 객체의 생성자(<code>new RegExp('ab+c')</code>)를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.</p> + +<h3 id="생성자의_플래그">생성자의 플래그</h3> + +<p>ECMAScript 6부터는 <code>new RegExp(/ab+c/, 'i')</code>처럼, 첫 매개변수가 <code>RegExp</code>이면서 <code>flags</code>를 지정해도 {{jsxref("TypeError")}} (<code>"can't supply flags when constructing one RegExp from another"</code>)가 발생하지 않고, 매개변수로부터 새로운 정규 표현식을 생성합니다.</p> + +<p>생성자 함수를 사용할 경우 보통의 문자열 이스케이프 규칙(특수 문자를 문자열에 사용할 때 앞에 역빗금(<code>\</code>)을 붙이는 것)을 준수해야 합니다.</p> + +<p>예를 들어 다음 두 줄은 동일한 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">let re = /\w+/ +let re = new RegExp('\\w+')</pre> + +<h3 id="Perl_형태의_RegExp_속성">Perl 형태의 <code>RegExp</code> 속성</h3> + +<p>일부 {{JSxRef("RegExp")}} 속성은 같은 값에 대해 긴 이름과 짧은 (Perl 형태의) 이름 모두 가지고 있습니다. (Perl은 JavaScript가 정규 표현식을 만들 때 참고한 프로그래밍 언어입니다.)<a href="https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features#RegExp_Properties"> 사용하지 않는 <code>RegExp</code> 속성</a>을 참고하세요.</p> + +<h2 id="생성자">생성자</h2> + +<dl> + <dt>{{jsxref("RegExp/RegExp", "RegExp()")}}</dt> + <dd>새로운 <code>RegExp</code> 객체를 생성합니다.</dd> +</dl> + +<h2 id="정적_속성">정적 속성</h2> + +<dl> + <dt>{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}</dt> + <dd>파생 객체를 생성할 때 사용하는 생성자입니다.</dd> + <dt>{{jsxref("RegExp.lastIndex")}}</dt> + <dd>다음 판별을 시작할 인덱스입니다.</dd> +</dl> + +<h2 id="인스턴스_속성">인스턴스 속성</h2> + +<dl> + <dt>{{JSxRef("RegExp.prototype.flags")}}</dt> + <dd><code>RegExp</code> 객체의 플래그를 담은 문자열입니다.</dd> + <dt>{{JSxRef("RegExp.prototype.dotAll")}}</dt> + <dd><code>.</code>이 줄 바꿈에 일치하는지 여부를 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.global")}}</dt> + <dd>정규 표현식이 문자열 내에서 가능한 모든 경우에 일치하는지, 아니면 최초에 대해서만 일치하는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.ignoreCase")}}</dt> + <dd>문자열의 대소문자를 구분하는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.multiline")}}</dt> + <dd>여러 줄에 걸쳐 탐색할 것인지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.source")}}</dt> + <dd>패턴을 나타내는 문자열입니다.</dd> + <dt>{{JSxRef("RegExp.prototype.sticky")}}</dt> + <dd>검색이 접착(sticky)되어있는지 나타냅니다.</dd> + <dt>{{JSxRef("RegExp.prototype.unicode")}}</dt> + <dd>Unicode 기능의 활성화 여부입니다.</dd> +</dl> + +<h2 id="인스턴스_메서드">인스턴스 메서드</h2> + +<dl> + <dt>{{JSxRef("RegExp.prototype.compile()")}}</dt> + <dd>스크립트 실행 중 정규 표현식을 (다시) 컴파일합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.exec()")}}</dt> + <dd>문자열 매개변수에 대해 검색을 실행합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.test()")}}</dt> + <dd>문자열 매개변수에 대해 판별을 실행합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.toString()")}}</dt> + <dd>객체의 문자열 표현을 반환합니다. {{JSxRef("Object.prototype.toString()")}} 메서드를 재정의합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 결과를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 모든 결과를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}</dt> + <dd>주어진 문자열 내의 일치를 새로운 문자열로 대치합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}</dt> + <dd>주어진 문자열에 대해 일치하는 인덱스를 반환합니다.</dd> + <dt>{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}</dt> + <dd>주어진 문자열을 분할해 배열로 반환합니다.</dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="정규_표현식을_사용해서_데이터_형식_바꾸기">정규 표현식을 사용해서 데이터 형식 바꾸기</h3> + +<p>다음 스크립트에서는 {{jsxref("String")}} 객체의 {{jsxref("String.prototype.replace()", "replace()")}} 메서드를 사용하여 <em>이름 성씨</em> 형태의 이름을 <em>성씨, 이름</em> 형태 바꿔 반환합니다.</p> + +<p>대치 문자열에는 <code>$1</code>과 <code>$2</code>를 사용하여 정규 표현식 패턴의 각 괄호에 일치한 결과를 받아옵니다.</p> + +<pre class="brush: js notranslate">let re = /(\w+)\s(\w+)/ +let str = 'John Smith' +let newstr = str.replace(re, '$2, $1') +console.log(newstr)</pre> + +<p>실행 결과는 <code>"Smith, John"</code>입니다.</p> + +<h3 id="정규_표현식을_사용해서_여러_가지_줄_바꿈_문자가_있는_문자열_나누기">정규 표현식을 사용해서 여러 가지 줄 바꿈 문자가 있는 문자열 나누기</h3> + +<p>기본 줄 바꿈 문자는 플랫폼(Unix, Windows 등)마다 다릅니다. 아래의 분할 스크립트는 모든 플랫폼의 줄 바꿈을 인식합니다.</p> + +<pre class="brush: js notranslate">let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end' +let lines = text.split(/\r\n|\r|\n/) +console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]</pre> + +<p>정규 표현식 패턴의 순서를 바꾸면 작동하지 않을 수 있습니다.</p> + +<h3 id="여러_줄에서_정규_표현식_사용하기">여러 줄에서 정규 표현식 사용하기</h3> + +<pre class="brush: js notranslate">let s = 'Please yes\nmake my day!' + +s.match(/yes.*day/); +// Returns null + +s.match(/yes[^]*day/); +// Returns ["yes\nmake my day"]</pre> + +<h3 id="접착_플래그와_함께_사용하기">접착 플래그와 함께 사용하기</h3> + +<p>{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}} 플래그는 해당 정규 표현식이 접착 판별, 즉 {{jsxref("RegExp.prototype.lastIndex")}}에서 시작하는 일치만 확인하도록 할 수 있습니다.</p> + +<pre class="brush: js notranslate">let str = '#foo#' +let regex = /foo/y + +regex.lastIndex = 1 +regex.test(str) // true +regex.lastIndex = 5 +regex.test(str) // false (lastIndex is taken into account with sticky flag) +regex.lastIndex // 0 (reset after match failure)</pre> + +<h3 id="접착과_전역_플래그의_차이">접착과 전역 플래그의 차이</h3> + +<p>접착 플래그 <code>y</code>의 일치는 정확히 <code>lastIndex</code> 위치에서만 발생할 수 있으나, 전역 플래그 <code>g</code>의 경우 <code>lastIndex</code> 또는 그 이후에서도 발생할 수 있습니다.</p> + +<pre class="brush: js notranslate">re = /\d/y; +while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); + +// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1 +// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2 +// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3 +// ... and no more match.</pre> + +<p>전역 플래그 <code>g</code>를 사용했다면, 3개가 아니고 6개 숫자 모두 일치했을 것입니다.</p> + +<h3 id="정규_표현식과_Unicode_문자">정규 표현식과 Unicode 문자</h3> + +<p> <code>\w</code>와 <code>\W</code>는 <code>a</code>부터 <code>z</code>, <code>A</code>부터 <code>Z</code>, <code>0</code>부터 <code>9</code> <code>_</code> 등의 {{glossary("ASCII")}} 문자에만 일치합니다.</p> + +<p>러시아어나 히브리어와 같은 다른 언어의 문자까지 일치하려면 <code>\uhhhh</code>(이때 hhhh는 해당 문자의 16진법 Unicode 값) 문법을 사용하세요. 아래 예제에서는 문자열에서 Unicode 문자를 추출합니다.</p> + +<pre class="brush: js notranslate">let text = 'Образец text на русском языке' +let regex = /[\u0400-\u04FF]+/g + +let match = regex.exec(text) +console.log(match[0]) // logs 'Образец' +console.log(regex.lastIndex) // logs '7' + +let match2 = regex.exec(text) +console.log(match2[0]) // logs 'на' [did not log 'text'] +console.log(regex.lastIndex) // logs '15' + +// and so on</pre> + +<p><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escapes">유니코드 속성 이스케이프</a> 기능을 사용해 <code>\p{scx=Cyrl}</code>과 같은 간단한 구문으로 이 문제를 해결할 수 있습니다.</p> + +<h3 id="URL에서_서브도메인_추출하기">URL에서 서브도메인 추출하기</h3> + +<pre class="brush: js notranslate">let url = 'http://xxx.domain.com' +console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'</pre> + +<div class="blockIndicator note"> +<p>이 때는 정규표현식보단 <a href="/ko/docs/Web/API/URL_API">URL API</a>를 통해 브라우저에 내장된 URL 구문 분석기를 사용하는 것이 좋습니다.</p> +</div> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">명세</th> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<div>{{Compat("javascript.builtins.RegExp")}}</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/n/index.html b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html new file mode 100644 index 0000000000..5b6706cad2 --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/n/index.html @@ -0,0 +1,66 @@ +--- +title: RegExp.$1-$9 +slug: Web/JavaScript/Reference/Global_Objects/RegExp/n +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/n +--- +<div>{{JSRef}} {{non-standard_header}}</div> + +<p>비표준 <strong>$1, $2, $3, $4, $5, $6, $7, $8, $9 </strong>속성들은 정적이며, 괄호로 묶인 하위 문자열 match들을 포함하는 정규 표현식의 읽기 전용 속성들입니다.</p> + +<h2 id="Syntax">Syntax</h2> + +<pre class="syntaxbox"><code><var>RegExp</var>.$1 +RegExp.$2</code> +RegExp.$3 +RegExp.$4 +RegExp.$5 +RegExp.$6 +RegExp.$7 +RegExp.$8 +RegExp.$9 +</pre> + +<h2 id="Description">Description</h2> + +<p>$1, ..., $9 properties are static, they are not a property of an individual regular expression object. Instead, you always use them as <code>RegExp.$1</code>, ..., <code>RegExp.$9</code>.</p> + +<p>The values of these properties are read-only and modified whenever successful matches are made.</p> + +<p>The number of possible parenthesized substrings is unlimited, but the <code>RegExp</code> object can only hold the first nine. You can access all parenthesized substrings through the returned array's indexes.</p> + +<p>These properties can be used in the replacement text for the {{jsxref("String.replace")}} method. When used this way, do not prepend them with <code>RegExp</code>. The example below illustrates this. When parentheses are not included in the regular expression, the script interprets <code>$n</code>'s literally (where <code>n</code> is a positive integer).</p> + +<h2 id="Examples">Examples</h2> + +<h3 id="Using_n_with_String.replace">Using <code>$n</code> with <code>String.replace</code></h3> + +<p>아래의 script는 first last 포맷의 이름과 매치하기 위해 {{jsxref("String")}} 인스턴스의 {{jsxref("String.prototype.replace()", "replace()")}} 메소드를 사용하고 그것을 last, first 포맷으로 출력한다. 대체 텍스트에서, 이 script는 정규 표현식 패턴에서 매칭되는 괄호들에 해당하는 결과들을 나타내는 <code>$1</code> 과 <code>$2</code> 를 사용한다.</p> + +<pre class="brush: js">var re = /(\w+)\s(\w+)/; +var str = 'John Smith'; +str.replace(re, '$2, $1'); // "Smith, John" +RegExp.$1; // "John" +RegExp.$2; // "Smith" +</pre> + +<h2 id="Specifications">Specifications</h2> + +<p>Non-standard. Not part of any current specification.</p> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.n")}}</p> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{non-standard_inline}} {{jsxref("RegExp.input", "RegExp.input ($_)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.lastMatch", "RegExp.lastMatch ($&)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.lastParen", "RegExp.lastParen ($+)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.leftContext", "RegExp.leftContext ($`)")}}</li> + <li>{{non-standard_inline}} {{jsxref("RegExp.rightContext", "RegExp.rightContext ($')")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html new file mode 100644 index 0000000000..387b5bceff --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/regexp/index.html @@ -0,0 +1,114 @@ +--- +title: RegExp() constructor +slug: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +tags: + - Constructor + - JavaScript + - Reference + - RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp +--- +<div>{{JSRef}}</div> + +<p><strong><code>RegExp</code></strong> 생성자는 패턴을 사용해 텍스트를 판별할 때 사용하는 정규 표현식 객체를 생성합니다.</p> + +<p>정규 표현식에 대한 소개는 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a>을 참고하세요.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}</div> + + + +<h2 id="구문">구문</h2> + +<p>리터럴, 생성자, 팩토리 표기법이 가능합니다.</p> + +<pre class="syntaxbox notranslate">/<var>pattern</var>/<var>flags</var> +new RegExp(<var>pattern</var>[, <var>flags</var>]) +RegExp(<var>pattern</var>[, <var>flags</var>]) +</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>pattern</var></code></dt> + <dd>정규 표현식을 나타내는 텍스트.</dd> + <dd>ES5부터는, 생성자 표기법에 한정하여 다른 <code>RegExp</code> 객체 혹은 리터럴을 사용할 수 있습니다. 패턴은 <a href="/ko/docs/Web/JavaScript/Guide/정규식#특수_문자_사용하기">특수 문자</a>를 포함할 수 있어서 일반적인 문자열 리터럴보다 더 넓은 범위의 값을 판별할 수 있습니다.</dd> + <dt><code><var>flags</var></code></dt> + <dd> + <p>정규 표현식에 추가할 플래그.</p> + + <p>정규 표현식 객체를 패턴으로 제공한 경우 <code><var>flags</var></code> 문자열은 제공한 객체의 플래그를 모두 대체하며 <code>lastIndex</code>를 <code>0</code>으로 초기화합니다. (ES2015 이후)</p> + + <p><code><var>flags</var></code>를 지정하지 않았으면서 정규 표현식 객체를 제공한 경우, 해당 객체의 플래그와 <code>lastIndex</code>를 복제합니다.</p> + + <p><code>flags</code>는 다음 문자를 조합하여 지정할 수 있습니다.</p> + + <dl> + <dt><code>g</code> (global, 전역 판별)</dt> + <dd>처음 일치에서 중단하지 않고, 문자열 전체를 판별합니다.</dd> + <dt><code>i</code> (ignore case, 대소문자 무시)</dt> + <dd><code>u</code> 플래그까지 활성화된 경우, Unicode 대소문자 폴딩을 사용합니다.</dd> + <dt><code>m</code> (multiline, 여러 줄)</dt> + <dd>시작과 끝 문자(<code>^</code>과 <code>$</code>)가 여러 줄에 걸쳐 동작합니다. 즉, 전체 입력 문자열의 맨 처음과 맨 끝 뿐만 아니라 (<code>\n</code>이나 <code>\r</code>로 구분되는) <u>각각의</u> 줄의 처음과 끝도 일치합니다.</dd> + <dt><code>s</code> ("dotAll")</dt> + <dd><code>.</code>이 줄 바꿈에도 일치합니다.</dd> + <dt><code>u</code> (unicode)</dt> + <dd><code><var>pattern</var></code>을 Unicode 코드 포인트 시퀀스로 처리합니다. (<a href="/ko/docs/Web/API/DOMString/Binary">이진 문자열</a> 참고)</dd> + <dt><code>y</code> (sticky, 접착)</dt> + <dd>이 정규 표현식의 <code>lastIndex</code> 속성에 명시된 인덱스에서만 판별하고, 이전/이후 인덱스에서 판별을 시도하지 않습니다.</dd> + </dl> + </dd> +</dl> + +<h2 id="예제">예제</h2> + +<h3 id="리터럴_표기법과_생성자">리터럴 표기법과 생성자</h3> + +<p><code>RegExp</code> 객체는 리터럴 표기법과 생성자로써 생성할 수 있습니다.</p> + +<ul> + <li><strong>리터럴 표기법</strong>의 매개변수는 두 빗금으로 감싸야 하며 따옴표를 사용하지 않습니다.</li> + <li><strong>생성자 함수</strong>의 매개변수는 빗금으로 감싸지 않으나 따옴표를 사용합니다.</li> +</ul> + +<p>다음의 세 표현식은 모두 같은 정규 표현식을 생성합니다.</p> + +<pre class="brush: js notranslate">/ab+c/i +new RegExp(/ab+c/, 'i') // 리터럴 +new RegExp('ab+c', 'i') // 생성자 +</pre> + +<p>리터럴 표기법은 표현식을 평가할 때 정규 표현식을 컴파일합니다. 정규 표현식이 변하지 않으면 리터럴 표기법을 사용하세요. 예를 들어, 반복문 안에서 사용할 정규 표현식을 리터럴 표기법으로 생성하면 정규 표현식을 매번 다시 컴파일하지 않습니다.</p> + +<p>정규 표현식 객체의 생성자(<code>new RegExp('ab+c')</code>)를 사용하면 정규 표현식이 런타임에 컴파일됩니다. 패턴이 변할 가능성이 있거나, 사용자 입력과 같이 알 수 없는 외부 소스에서 가져오는 정규 표현식의 경우 생성자 함수를 사용하세요.</p> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp-constructor', 'RegExp constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + +<div> + + +<p>{{Compat("javascript.builtins.RegExp.RegExp")}}</p> +</div> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("String.prototype.match()")}}</li> + <li>{{jsxref("String.prototype.replace()")}}</li> +</ul> diff --git a/files/ko/web/javascript/reference/global_objects/regexp/test/index.html b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html new file mode 100644 index 0000000000..07569e7eaf --- /dev/null +++ b/files/ko/web/javascript/reference/global_objects/regexp/test/index.html @@ -0,0 +1,129 @@ +--- +title: RegExp.prototype.test() +slug: Web/JavaScript/Reference/Global_Objects/RegExp/test +tags: + - JavaScript + - Method + - Prototype + - Reference + - RegExp + - 정규 표현식 + - 정규식 +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test +--- +<div>{{JSRef}}</div> + +<p><strong><code>test()</code></strong> 메서드는 주어진 문자열이 정규 표현식을 만족하는지 판별하고, 그 여부를 <code>true</code> 또는 <code>false</code>로 반환합니다.</p> + +<div>{{EmbedInteractiveExample("pages/js/regexp-prototype-test.html", "taller")}}</div> + + + +<h2 id="구문">구문</h2> + +<pre class="syntaxbox notranslate"><var>regexObj</var>.test(<var>str</var>)</pre> + +<h3 id="매개변수">매개변수</h3> + +<dl> + <dt><code><var>str</var></code></dt> + <dd>정규 표현식 일치를 수행할 문자열.</dd> +</dl> + +<h3 id="반환_값">반환 값</h3> + +<p>주어진 문자열 <code>str</code> 중 정규 표현식이 일치하는 부분이 있으면 <code>true</code>, 아니면, <code>false</code>.</p> + +<h2 id="설명">설명</h2> + +<p>패턴이 문자열 내에 존재하는지에 대한 여부를 알아보고자 할 때 <code>test()</code>를 사용하세요. 일치의 위치 인덱스, 또는 일치하지 않으면 <code>-1</code>을 반환하는 {{jsxref("String.prototype.search()")}}와 달리 <code>test()</code>는 불리언을 반환합니다.</p> + +<p>더 느리지만 더 많은 정보가 필요하면 {{jsxref("RegExp.prototype.exec()", "exec()")}} 메서드를 사용하세요. ({{jsxref("String.prototype.match()")}} 메서드와 비슷합니다.)</p> + +<p><code>exec()</code>처럼, <code>test()</code>도 전역 탐색 플래그를 제공한 정규 표현식에서 여러 번 호출하면 이전 일치 이후부터 탐색합니다. <code>exec()</code>와 <code>test()</code>를 혼용해 사용하는 경우에도 해당됩니다.</p> + +<h2 id="예제">예제</h2> + +<h3 id="test_사용하기"><code>test()</code> 사용하기</h3> + +<p>문자열의 맨 처음에 <code>"hello"</code>가 포함됐는지 알아보는 간단한 예제 코드입니다.</p> + +<pre class="brush: js notranslate">const str = 'hello world!'; +const result = /^hello/.test(str); + +console.log(result); // true +</pre> + +<p>다음은 일치 여부에 따라 다른 메시지를 기록하는 예제입니다.</p> + +<pre class="brush: js notranslate">function testInput(re, str) { + let midstring; + if (re.test(str)) { + midstring = 'contains'; + } else { + midstring = 'does not contain'; + } + console.log(`${str} ${midstring} ${re.source}`); +} +</pre> + +<h3 id="전역_플래그와_test">전역 플래그와 <code>test()</code></h3> + +<p>정규 표현식에 <a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions#플래그를_사용한_고급검색">전역 플래그</a>를 설정한 경우, <code>test()</code> 메서드는 정규 표현식의 {{jsxref("RegExp.lastIndex", "lastIndex")}}를 업데이트합니다. ({{jsxref("RegExp.prototype.exec()")}}도 <code>lastIndex</code> 속성을 업데이트합니다.)</p> + +<p><code>test(<var>str</var>)</code>을 또 호출하면 <code><var>str</var></code> 검색을 <code>lastIndex</code>부터 계속 진행합니다. <code>lastIndex</code> 속성은 매 번 <code>test()</code>가 <code>true</code>를 반환할 때마다 증가하게 됩니다.</p> + +<div class="blockIndicator note"> +<p><strong>참고:</strong> <code>test()</code>가 <code>true</code>를 반환하기만 하면 <code>lastIndex</code>는 초기화되지 않습니다. 심지어 이전과 다른 문자열을 매개변수로 제공해도 그렇습니다!</p> +</div> + +<p><code>test()</code>가 <code>false</code>를 반환할 땐 <code>lastIndex</code> 속성이 <code>0</code>으로 초기화됩니다.</p> + +<p>이 행동에 대한 예제가 다음 코드입니다.</p> + +<pre class="brush: js notranslate">const regex = /foo/g; // the "global" flag is set + +// regex.lastIndex is at 0 +regex.test('foo') // true + +// regex.lastIndex is now at 3 +regex.test('foo') // false + +// regex.lastIndex is at 0 +regex.test('barfoo') // true + +// regex.lastIndex is at 6 +regex.test('foobar') //false + +// regex.lastIndex is at 0 +// (...and so on) +</pre> + +<h2 id="명세">명세</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-regexp.prototype.test', 'RegExp.test')}}</td> + </tr> + </tbody> +</table> + +<h2 id="브라우저_호환성">브라우저 호환성</h2> + + + +<p>{{Compat("javascript.builtins.RegExp.test")}}</p> + +<h2 id="같이_보기">같이 보기</h2> + +<ul> + <li><a href="/ko/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript 안내서의 정규 표현식 장</a></li> + <li>{{jsxref("RegExp")}}</li> + <li>{{jsxref("RegExp.prototype")}}</li> +</ul> |